/*
 * Popup Window
 * @author windstream
 */
function popWin(url, wn, wd, ht, scroll)
{
	useScroll = 1;
	width = 600;
	height = 620;
	winName = "newWin";
	if (scroll == 0) {
		useScroll = 0;
	}
	if (ht != null) {
		height = ht;
	}
	if (wd != null) {
		width = wd;
	}
	if (wn != null) {
		winName = wn;
	}
	thisURL = url;
	popupWin = window.open(thisURL, winName, "width=" + width + ",height=" + height + ", scrollbars=" + useScroll + ",resizable");
}

/*
 * Popup Window
 * @author windstream
 */
function TivopopWin(url, wn, wd, ht, scroll)
{
	useScroll = 1;
	width = 750;
	height = 575;
	winName = "newWin";
	if (scroll == 0) {
		useScroll = 0;
	}
	if (ht != null) {
		height = ht;
	}
	if (wd != null) {
		width = wd;
	}
	if (wn != null) {
		winName = wn;
	}
	thisURL = url;
	popupWin = window.open(thisURL, winName, "width=" + width + ",height=" + height + ", scrollbars=" + useScroll + ",resizable");
}

/*
 * Windstream jQuery Namespace
 */
jQuery.windstream = {};
jQuery.windstream.activeProduct = {}; 
jQuery.windstream.activeProduct.index = 0;
jQuery.windstream.activeProduct.id = 0;
jQuery.windstream.debug = false;
jQuery.windstream.isLoadingProduct = false;
jQuery.windstream.isProcessingOrder = false;

/**
 * Used to encode string for url passing
 */
function urlencode(str)
{
    var histogram = {}, tmp_arr = [];
    var ret = (str+'').toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    histogram['\u00DC'] = '%DC';
    histogram['\u00FC'] = '%FC';
    histogram['\u00C4'] = '%D4';
    histogram['\u00E4'] = '%E4';
    histogram['\u00D6'] = '%D6';
    histogram['\u00F6'] = '%F6';
    histogram['\u00DF'] = '%DF';
    histogram['\u20AC'] = '%80';
    histogram['\u0081'] = '%81';
    histogram['\u201A'] = '%82';
    histogram['\u0192'] = '%83';
    histogram['\u201E'] = '%84';
    histogram['\u2026'] = '%85';
    histogram['\u2020'] = '%86';
    histogram['\u2021'] = '%87';
    histogram['\u02C6'] = '%88';
    histogram['\u2030'] = '%89';
    histogram['\u0160'] = '%8A';
    histogram['\u2039'] = '%8B';
    histogram['\u0152'] = '%8C';
    histogram['\u008D'] = '%8D';
    histogram['\u017D'] = '%8E';
    histogram['\u008F'] = '%8F';
    histogram['\u0090'] = '%90';
    histogram['\u2018'] = '%91';
    histogram['\u2019'] = '%92';
    histogram['\u201C'] = '%93';
    histogram['\u201D'] = '%94';
    histogram['\u2022'] = '%95';
    histogram['\u2013'] = '%96';
    histogram['\u2014'] = '%97';
    histogram['\u02DC'] = '%98';
    histogram['\u2122'] = '%99';
    histogram['\u0161'] = '%9A';
    histogram['\u203A'] = '%9B';
    histogram['\u0153'] = '%9C';
    histogram['\u009D'] = '%9D';
    histogram['\u017E'] = '%9E';
    histogram['\u0178'] = '%9F';
    
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret)
    }
    
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}

/*
 * Calculate items total Height for containing div.
 */
function setFrameHeight(contentHeight)
{
	var products = jQuery('#openProducts .itemHeader').length;
	var headfoot = 47;
	var content = 0;
	var contentItems = jQuery('.itemContent');
	if (!contentHeight) {
		var i=0;
		for (i=0; i<contentItems.length; i++) {
			if (jQuery(contentItems[i]).css('display') == 'block') {
				//alert(jQuery(contentItems[i]).css('height') + ' - ' + jQuery(contentItems[i]).attr('id'));
				content = parseInt(jQuery(contentItems[i]).css('height').replace('px', ''));
			}
		}
	} else {
		//alert(contentHeight);
		content = parseInt(contentHeight.replace('px', ''));
	}
	//var content = 241;
	var newHeight = ((headfoot * products) + content) + 3;
	//var newHeight = 
	jQuery('#openProducts-frame').css('height', newHeight);
	var cartHeight = newHeight - (9 + 23 + 14 + 35 + 6 + 10 + (jQuery('.cartLegal').height));
	jQuery('#shoppingCartContainer .content').css('height','');
	if(jQuery('#shoppingCartContainer .content').height() < cartHeight) {
		jQuery('#shoppingCartContainer .content').css('height', cartHeight);
	}
}

/*
 * Set active Product in namespace.
 */
function setActive(e, ui) {
	jQuery.windstream.activeProduct.id = ui.newHeader.attr('id').replace('productHeader_','');
	jQuery('#openProducts .itemHeader').each(function(i) {
		if(this.id==ui.newHeader.attr('id')) {
			jQuery.windstream.activeProduct.index = i;
			jQuery.windstream.activeProduct.id = this.id;
		}
	});
}

/*
 * Product Open/Close functions
 */
function openProductsLoader(loadState)
{
	switch(loadState) {
		case 'show':
			var width = jQuery('#openProducts-frame').width();
			var height = jQuery('#openProducts-frame').height();
			var position = jQuery('#openProducts-frame').position();
			jQuery('#openProductsLoader').show();
			jQuery('#openProductsLoader').css({'left' : position.left, 'top' : position.top});
			jQuery('#openProductsLoader').width(width);
			jQuery('#openProductsLoader').height(height);
			break;
		case 'hide':
			jQuery('#openProductsLoader').hide();
			break;
		default:
	}
}
 
function loadInfo(e)
{
	if (jQuery.windstream.isLoadingProduct != true) {
		jQuery.windstream.isLoadingProduct = true;
		scroll(0, 0);
		jQuery(this).unbind('click');
		jQuery(this).removeClass('loadHookLoaded');
		var side = jQuery(this).parent().attr('class');
		var type = jQuery(this).parent().parent().parent().attr('class');
		
		side = side.substr(0,1).toUpperCase() + side.substr(1);
		
		jQuery(this).children().each(function(i) {
			if(jQuery(this).hasClass('overlay')) {
				jQuery(this).show();
			}
		});
		var pid = this.id;
		var id = pid.replace('load_product_', '');
		
		jQuery.post('/showcase/index/session/', {
				ajaxAction: 'open',
				productId: id
			},
			function(data) {
			}
		);
		openProductsLoader('show');
		jQuery.getJSON('/showcase/index/getproduct/pid/' + id, {}, openProduct);
	}
}

var openProductJson = null;

function openProduct(json) {
	openProductJson = json;
	jQuery.get('/showcase/index/getcontentwell/pid/' + json.id, {}, openProductPart2);
}

function openProductPart2(theData)
{
	var json = openProductJson;
	var id = json.id;
	var jsonTitle = json.name;
	var product = document.createElement('div');
	product.className = 'itemHeader';
	product.setAttribute('id', 'productHeader_' + id);
	if (jQuery('#load_product_' + id).hasClass('protection')) {
		json.type = 'protection';
	} else if (jQuery('#load_product_' + id).hasClass('service')) {
		json.type = 'service';
	} else if (jQuery('#load_product_' + id).hasClass('product')) {
		json.type = 'product';
	}
	jQuery(product).addClass(json.type + 'Item');
	
	var title = document.createElement('div');
	title.className = 'title';
	title.setAttribute('title',jsonTitle);
	
	var titleImg = document.createElement('img');
	titleImg.setAttribute('src', '/showcase/index/generateimage/text/' + jsonTitle + '/');
	titleImg.setAttribute('alt', jsonTitle);
	titleImg.setAttribute('title', jsonTitle);

	title.appendChild(titleImg);
	product.appendChild(title);
	
	var buttons = document.createElement('div');
	buttons.className = 'buttons';

	var addProduct = document.createElement('img');
	addProduct.setAttribute('src', '/showcase/images/layout/default/buttons/btn_add_' + json.type + '.gif');
	addProduct.setAttribute('width', '102');
	addProduct.setAttribute('height', '27');
	addProduct.setAttribute('alt', 'ADD TO CART');
	addProduct.setAttribute('title', 'ADD TO CART');
	addProduct.setAttribute('id', 'add_product_' + id);
	addProduct.className = 'addButton';
	jQuery(addProduct).bind('click', addToCart);
	
	buttons.appendChild(addProduct);
	
	var closeProduct_elm = document.createElement('img');
	closeProduct_elm.setAttribute('src', '/showcase/images/layout/default/buttons/btn_close_' + json.type + '.gif');
	closeProduct_elm.setAttribute('width', '122');
	closeProduct_elm.setAttribute('height', '27');
	closeProduct_elm.setAttribute('alt', 'CLOSE PRODUCT');
	closeProduct_elm.setAttribute('title', 'CLOSE PRODUCT');
	closeProduct_elm.setAttribute('id', 'close_product_' + id);
	closeProduct_elm.className = 'closeButton';

	buttons.appendChild(closeProduct_elm);

	product.appendChild(buttons);
	
	var arrow = document.createElement('div');
	arrow.className = 'arrow';
	arrow.innerHTML = '&nbsp;';

	product.appendChild(arrow);

	jQuery('#openProducts').append(product);
	
	jQuery('#openProducts').append(theData);
	
	var productFooter = document.createElement('div');
	productFooter.setAttribute('id','productFooter_' + id);
	productFooter.className = 'itemFooter';
	productFooter.innerHTML = '&nbsp;';
	jQuery(productFooter).addClass(json.type + 'Item');

	jQuery('#openProducts').append(productFooter);
	
	setFrameHeight();
	var total = jQuery('#openProducts .itemHeader').length;
	//var curActive = jQuery('#openProducts').accordion('option', 'active');
	var toActivate = total - 1;
	jQuery('#openProducts').accordion('destroy');
	jQuery('#openProducts').accordion({
		autoHeight: false,
		active: jQuery.windstream.activeProduct.index,
		header: '.itemHeader',
		changestart: function(event, ui) {
			lastContentHeight = jQuery(ui.newContent.parent().get(0)).css('height');
			setFrameHeight(lastContentHeight);
		},
		change: aChange
	});
	jQuery('#openProducts').accordion('activate', toActivate);
	if(total>1) {
		jQuery('#openProducts .closeButton').each(function(i) {
			var pid = this.id;
			var id = pid.replace('close_product_','');
			var inCart = jQuery('#productContainer_' + id);
			if(inCart.length==0) {
				jQuery(this).show();
				jQuery(this).bind('click', closeProduct);
			}
		});
	}
	jQuery.windstream.isLoadingProduct = false;
	openProductsLoader('hide');
}

function closeProduct(e) {
	var pid = this.id;
	var id = pid.replace('close_product_','');
	var curPos = 0;
	
	jQuery('#openProducts .itemHeader').each(function(i) {
		if(this.id=='productHeader_' + id) {
			curPos = i;
		}
	});
	
	jQuery('#productHeader_' + id).remove();
	jQuery('#productContent_' + id).remove();
	jQuery('#productFooter_' + id).remove();

	jQuery.post('/showcase/index/session/',
		{
			ajaxAction: 'close',
			productId: id
		},
		function(data) {
		}
	);
	
//	setFrameHeight();
	var total = jQuery('#openProducts .itemHeader').length;
	if(curPos == jQuery.windstream.activeProduct.index) {
		jQuery.windstream.activeProduct.index = total - 1;
	} else if(curPos < jQuery.windstream.activeProduct.index) {
		if(jQuery.windstream.activeProduct.index != 0) {
			jQuery.windstream.activeProduct.index = jQuery.windstream.activeProduct.index - 1;
		}
	}
	
	jQuery('#openProducts').accordion('destroy');
	jQuery('#openProducts').accordion({
		autoHeight: false,
		active: jQuery.windstream.activeProduct.index,
		header: '.itemHeader',
		changestart: function(event, ui) {
			lastContentHeight = jQuery(ui.newContent.parent().get(0)).css('height');
			setFrameHeight(lastContentHeight);
		},
		change: aChange
	});
	if (total < 2) {
		jQuery('#openProducts .closeButton').each(function(i) {
			jQuery(this).unbind('click');
			jQuery(this).hide();
		});
	}

	var loadProduct = jQuery('#load_product_' + id);
	if (loadProduct.length != 0) {
		var side = loadProduct.parent().attr('class');
		var type = loadProduct.parent().parent().parent().attr('class');
		side = side.substr(0,1).toUpperCase() + side.substr(1);
		loadProduct.addClass('loadHookLoaded');
		loadProduct.bind('click', loadInfo);
		loadProduct.children().each(function(i) {
			if(jQuery(this).hasClass('overlay')) {
				jQuery(this).hide();
			}
		});
	}
	setFrameHeight();
}

/*
 * Cart Functions
 */
/** Loading DIV **/
function shoppingCartLoader(loadState) {
	switch(loadState) {
		case 'show':
			var width = jQuery('#shoppingCartContainer').width();
			var height = jQuery('#shoppingCartContainer .content').height()  + jQuery('#shoppingCartContainer .checkout').height();
			var position = jQuery('#shoppingCartContainer .content').position();
			jQuery('#shoppingCartLoader').show();
			jQuery('#shoppingCartLoader'). css({ 'left' : position.left, 'top' : position.top });
			jQuery('#shoppingCartLoader').width(width);
			jQuery('#shoppingCartLoader').height(height);
			break;
		case 'hide':
			jQuery('#shoppingCartLoader').hide();
			break;
		default:
	}
}
 
/** ADD ITEM **/
function addItem(id, title)
{
	var itemContainer = document.createElement('div');
	
	itemContainer.className = 'productContainer';
	itemContainer.setAttribute('id', 'productContainer_' + id);
	var item = document.createElement('div');
	item.setAttribute('id', 'productTitle_' + id);
	item.className = 'productTitle';
	//item.innerHTML = title;

	var itemPrice = document.createElement('div');
	itemPrice.setAttribute('id', 'productPrice_' + id);
	itemPrice.className = 'productPrice';

	var itemSpeed = document.createElement('div');
	itemSpeed.setAttribute('id', 'productSpeed_' + id);
	itemSpeed.className = 'productSpeed';

	var itemRebates = document.createElement('div');
	itemRebates.setAttribute('id', 'productRebates_' + id);
	itemRebates.className = 'productRebates';

	var itemFees = document.createElement('div');
	itemFees.setAttribute('id', 'productFees_' + id);
	itemFees.className = 'productFees';

	var itemPromotions = document.createElement('div');
	itemPromotions.setAttribute('id', 'productPromotions_' + id);
	itemPromotions.className = 'productPromotions';

	var itemShippingFees = document.createElement('div');
	itemShippingFees.setAttribute('id', 'productShippingFees_' + id);
	itemShippingFees.className = 'productShippingFees';
	
	var itemCheckboxContainer = document.createElement('div');
	itemCheckboxContainer.className = 'productCheckbox';
	
	var itemCheckbox = document.createElement('img');
	itemCheckbox.setAttribute('id', 'productRemove_' + id);
	itemCheckbox.setAttribute('src', '/showcase/images/layout/default/trashcan.png');
	itemCheckbox.setAttribute('alt', 'Remove From Cart');
	itemCheckbox.setAttribute('title', 'Remove From Cart');
	itemCheckbox.className = 'removeFromCart'
	
	itemCheckboxContainer.appendChild(itemCheckbox);

	var clear = document.createElement('div');
	clear.style.fontSize = '1px';
	clear.style.height = '1px';
	clear.style.width = '100%';
	clear.style.clear = 'both';
	
	var jsonUrl = '/pid/' + id;
	if (jQuery('#productContent_' + id + ' .tiered:checked').length > 0) {
		jsonUrl += '/tier/' + jQuery('#productContent_' + id + ' .tiered:checked').val();
	}
	
	if (jQuery('#productContent_' + id + ' .tiered-addon:checked').length > 0) {
		jsonUrl += '/tieraddon/' + jQuery('#productContent_' + id + ' .tiered-addon:checked').val();
	}
	
	if (jQuery('#productContent_' + id + ' .addon:checked').length > 0) {
		jsonUrl += '/addon/' + jQuery('#productContent_' + id + ' .addon:checked').val();
	}
	
	if (jQuery('#productContent_' + id + ' .bundle:checked').length > 0) {
		jsonUrl += '/bundle/' + jQuery('#productContent_' + id + ' .bundle:checked').val();
	}
	
	jQuery.getJSON('/showcase/index/getproductforcart' + jsonUrl, {}, function(json) {
		var html = '<span class="price">$' + json.price + '</span><br />';
		if (json.term != '') {
			 html += '<span class="term" style="font-size: 8px;">' + json.term + '</span>';
		}
		itemPrice.innerHTML = html;
		
		item.innerHTML = json.name;
		
		itemContainer.appendChild(itemCheckboxContainer);
		itemContainer.appendChild(item);
		itemContainer.appendChild(itemPrice);
		
		var attr = '';
		
		if (json.attributes) {
			for(i=0;i<json.attributes.length;i++) {
				if(json.attributes[i].type=='rebate') {
					itemRebates.innerHTML = itemRebates.innerHTML + '<div>' + json.attributes[i].name + '|' + json.attributes[i].value + '</div>';
				}
				if(json.attributes[i].type=='fee') {
					itemFees.innerHTML = itemFees.innerHTML + '<div>' + json.attributes[i].name + '|' + json.attributes[i].value + '</div>';
				}
				if(json.attributes[i].type=='promotion') {
					itemPromotions.innerHTML = itemPromotions.innerHTML + '<div>' + json.attributes[i].name + '|' + json.attributes[i].value + '</div>';
				}
				if(json.attributes[i].type=='shipping') {
					itemShippingFees.innerHTML = itemShippingFees.innerHTML + '<div>' + json.attributes[i].name + '|' + json.attributes[i].value + '</div>';
				}
			}
		}
		
		itemContainer.appendChild(itemRebates);
		itemContainer.appendChild(itemFees);
		itemContainer.appendChild(itemPromotions);
		itemContainer.appendChild(itemShippingFees);
		
		itemContainer.appendChild(clear);
		
		
		jQuery('#itemsInCart_' + json.term.replace(' ', '-')).append(itemContainer);
		
		jQuery('#productRemove_' + id).bind('click', removeFromCart);
		updateCart();
	});
}

/** TOTALS **/
function updateCart() {
	var itemsInCart = jQuery('.itemsInCart .productContainer');
	var totalObj = jQuery('#itemsTotal_one-time');
	var totalMonthObj = jQuery('#itemsTotal_per-month');
	totalObj.html('');
	totalMonthObj.html('');
	jQuery('#oneTimeOrderTitle').hide();
	jQuery('#monthlyServiceTitle').hide();
	if (itemsInCart.length > 0) {
		var isMonthly = false;
		var isOnce = false;
		var totalOnce = parseFloat(0.00);
		var totalMonth = parseFloat(0.00);
		productPrices = jQuery('.itemsInCart .productPrice .price');
		productTerms = jQuery('.itemsInCart .productPrice .term');
		productTerms.each(function(i) {
			if (this.innerHTML == 'one time') {
				isOnce = true;
				price = productPrices[i].innerHTML;
				if (price == 'FREE') {
					price = '$0.00';
				}
				price = price.substr(1, price.length - 1);
				totalOnce = parseFloat(totalOnce) + parseFloat(price);
			} else if (this.innerHTML == 'per month') {
				isMonthly = true;
				price = productPrices[i].innerHTML;
				if (price == 'FREE') {
					price = '$0.00';
				}
				price = price.substr(1, price.length - 1);
				totalMonth = parseFloat(totalMonth) + parseFloat(price);
			}
		});
		
		if(isMonthly) {
			jQuery('#monthlyServiceTitle').show();
			
			var totalMonthText = document.createElement('div');
			totalMonthText.className = 'totalText';
			totalMonthText.innerHTML = 'Total Monthly Fee';
			
			/*if(jQuery('.itemsInCart .productPromotions').children().length>0) {
				//totalMonthText.style.fontWeight = 'normal';
				jQuery(totalMonthText).css('font-weight','normal')
			}*/
			
			var totalMonthPrice = document.createElement('div');
			totalMonthPrice.className = 'totalPrice';
			totalMonthPrice.innerHTML = '$' + totalMonth.toFixed(2).toString();
			
			totalMonthObj.append(totalMonthText);
			totalMonthObj.append(totalMonthPrice);
	
			var div3 = document.createElement('div');
			div3.style.height = '1px';
			div3.style.fontSize = '1px';
			div3.style.clear = 'both';
			totalMonthObj.append(div3);
			
			productPromotions = jQuery('.itemsInCart .productPromotions');
			jQuery(productPromotions).each(function(i) {
				var thisChildren = jQuery(this).children();
				thisChildren.each(function(i) {
					var childValue = thisChildren[i].innerHTML;
					childValue = childValue.split('|');
					var promotionTitleObj = document.createElement('div');
					promotionTitleObj.className = 'totalText';
					promotionTitleObj.style.color = '#7dba00';
					promotionTitleObj.innerHTML = childValue[0];
					jQuery(promotionTitleObj).css('font-weight','normal')
					
					var promotionCostObj = document.createElement('div');
					promotionCostObj.className = 'totalPrice';
					promotionCostObj.innerHTML = '-$' + childValue[1];
					
					totalMonth = parseFloat(totalMonth) - parseFloat(childValue[1]);
					
					var div1 = document.createElement('div');
					div1.style.height = '1px';
					div1.style.fontSize = '1px';
					div1.style.clear = 'both';
					
					totalMonthObj.append(promotionTitleObj);
					totalMonthObj.append(promotionCostObj);
					totalMonthObj.append(div1);
				});
			});
			
			if(productPromotions.children().length>0) {
				var finalMonthText = document.createElement('div');
				finalMonthText.className = 'totalText';
				finalMonthText.innerHTML = 'Total Monthly Fee After Promotion';
				if(productPromotions.children().length>1) {
					finalMonthText.innerHTML = finalMonthText.innerHTML + 's';
				}
				finalMonthText.innerHTML = finalMonthText.innerHTML + '*';
				
				var finalMonthPrice = document.createElement('div');
				finalMonthPrice.className = 'totalPrice';
				finalMonthPrice.innerHTML = '$' + totalMonth.toFixed(2).toString();
				
				totalMonthObj.append(finalMonthText);
				totalMonthObj.append(finalMonthPrice);
				
				var div4 = document.createElement('div');
				div4.style.height = '1px';
				div4.style.fontSize = '1px';
				div4.style.clear = 'both';
				totalMonthObj.append(div4);
			}
		}
		
		if(isMonthly && isOnce) {
			var hr2 = document.createElement('hr');
			hr2.style.clear = 'both';
			totalMonthObj.append(hr2);
		}
		
		if(isOnce) {
			/*var hr = document.createElement('hr');
			hr.style.clear = 'both';
			totalObj.append(hr);*/
			
			jQuery('#oneTimeOrderTitle').show();
			
			var totalShippingCost = parseFloat(0.00); //TODO!
			var totalShippingItems = 0;
			
			productShippingFees = jQuery('.itemsInCart .productShippingFees');
			jQuery(productShippingFees).each(function(i) {
				var thisChildren = jQuery(this).children();
				thisChildren.each(function(i) {
					var childValue = thisChildren[i].innerHTML;
					childValue = childValue.split('|');
					totalShippingItems++;
					totalShippingCost = parseFloat(totalShippingCost) + parseFloat(childValue[1]);
				});
			});
			
			var totalShippingText = document.createElement('div');
			totalShippingText.className = 'totalText';
			//totalShippingText.style.fontWeight = 'normal';
			jQuery(totalShippingText).css('font-weight','normal')
			totalShippingText.innerHTML = 'Product Shipping (' + totalShippingItems + ')***';
			
			totalOnce = parseFloat(totalShippingCost) + parseFloat(totalOnce);
			
			var totalShippingPrice = document.createElement('div');
			totalShippingPrice.className = 'totalPrice';
			totalShippingPrice.innerHTML = '$' + totalShippingCost.toFixed(2).toString(); //TODO!
			
			if(totalShippingItems>0) {
				totalObj.append(totalShippingText);
				totalObj.append(totalShippingPrice);
			}
			
			var div1 = document.createElement('div');
			div1.style.height = '1px';
			div1.style.fontSize = '1px';
			div1.style.clear = 'both';
			totalObj.append(div1);
			
			productFees = jQuery('.itemsInCart .productFees');
			jQuery(productFees).each(function(i) {
				var thisChildren = jQuery(this).children();
				thisChildren.each(function(i) {
					var childValue = thisChildren[i].innerHTML;
					childValue = childValue.split('|');
					var feeTitleObj = document.createElement('div');
					feeTitleObj.className = 'totalText';
					jQuery(feeTitleObj).css('font-weight','normal')
					//feeTitleObj.style.fontWeight = 'normal';
					feeTitleObj.innerHTML = childValue[0];
					
					var feeCostObj = document.createElement('div');
					feeCostObj.className = 'totalPrice';
					feeCostObj.innerHTML = '$' + childValue[1];
					
					totalOnce = parseFloat(totalOnce) + parseFloat(childValue[1]);
					
					var div1 = document.createElement('div');
					div1.style.height = '1px';
					div1.style.fontSize = '1px';
					div1.style.clear = 'both';
					
					totalObj.append(feeTitleObj);
					totalObj.append(feeCostObj);
					totalObj.append(div1);
				});
			});
			
			var totalOnceText = document.createElement('div');
			totalOnceText.className = 'totalText';
			totalOnceText.innerHTML = 'Total One-Time Cost';
			
			if(jQuery('.itemsInCart .productRebates').children().length>0) {
				//totalOnceText.style.fontWeight = 'normal';
				jQuery(totalOnceText).css('font-weight','normal')
			}
			
			var totalOncePrice = document.createElement('div');
			totalOncePrice.className = 'totalPrice';
			totalOncePrice.innerHTML = '$' + totalOnce.toFixed(2).toString();
			
			totalObj.append(totalOnceText);
			totalObj.append(totalOncePrice);
			
			var div2 = document.createElement('div');
			div2.style.height = '1px';
			div2.style.fontSize = '1px';
			div2.style.clear = 'both';
			totalObj.append(div2);
			
			productRebates = jQuery('.itemsInCart .productRebates');
			jQuery(productRebates).each(function(i) {
				var thisChildren = jQuery(this).children();
				thisChildren.each(function(i) {
					var childValue = thisChildren[i].innerHTML;
					childValue = childValue.split('|');
					var rebateTitleObj = document.createElement('div');
					jQuery(rebateTitleObj).css('font-weight','normal')
					rebateTitleObj.className = 'totalText';
					rebateTitleObj.style.color = '#7dba00';
					rebateTitleObj.innerHTML = childValue[0];
					
					var rebateCostObj = document.createElement('div');
					rebateCostObj.className = 'totalPrice';
					jQuery(rebateTitleObj).css('font-weight','normal')
					rebateCostObj.innerHTML = '-$' + childValue[1];
					
					totalOnce = parseFloat(totalOnce) - parseFloat(childValue[1]);
					
					var div1 = document.createElement('div');
					div1.style.height = '1px';
					div1.style.fontSize = '1px';
					div1.style.clear = 'both';
					
					totalObj.append(rebateTitleObj);
					totalObj.append(rebateCostObj);
					totalObj.append(div1);
				});
			});
			
			if(productRebates.children().length>0) {
				var finalOnceText = document.createElement('div');
				finalOnceText.className = 'totalText';
				finalOnceText.innerHTML = 'Total One-Time Cost After Rebate**';
				if(productRebates.children().length>1) {
					finalOnceText.innerHTML = finalOnceText.innerHTML + 's';
				}
				
				var finalOncePrice = document.createElement('div');
				finalOncePrice.className = 'totalPrice';
				finalOncePrice.innerHTML = '$' + totalOnce.toFixed(2).toString();
				
				totalObj.append(finalOnceText);
				totalObj.append(finalOncePrice);
				
				var div3 = document.createElement('div');
				div3.style.height = '1px';
				div3.style.fontSize = '1px';
				div3.style.clear = 'both';
				totalObj.append(div3);
			}
		}
		
		jQuery('#shoppingCartCheckout').show();
	} else {
		var cartEmpty = document.createElement('div');
		cartEmpty.className = 'emptyCart';
		cartEmpty.innerHTML = '<img src="/showcase/index/generateimage/text/CART EMPTY/size/18/color/000000/" alt="EMPTY CART" />';
		jQuery('#removeFromCartTitle').hide();
		
		totalObj.html(cartEmpty);
		jQuery('#shoppingCartCheckout').hide();
	}
	shoppingCartLoader('hide');
	setFrameHeight();
}

/** ADD TO CART **/
function addToCart(e) {
	var pid = this.id.replace('add_product_', '');
	var parent = jQuery(this).parent().parent();
	var titleObj = jQuery(parent.get(0)).children('div.title').get(0);
	var title = jQuery(titleObj).attr('title');
	if (jQuery('#productContent_' + pid + ' .tiered').length > 0 || jQuery('#productContent_' + pid + ' .tiered-addon').length > 0) {
		if (jQuery('#productContent_' + pid + ' .tiered:checked').length < 1 && jQuery('#productContent_' + pid + ' .tiered-addon:checked').length < 1) {
			alert('Please select atleast one option before adding to your cart.');
			return false;
		}
	}
	
	
	shoppingCartLoader('show');
	
	var pdTier = '';
	if (jQuery('#productContent_' + pid + ' .tiered:checked').length > 0) {
		pdTier = jQuery('#productContent_' + pid + ' .tiered:checked').val();
	}
	
	var pdTierAddon = '';
	if (jQuery('#productContent_' + pid + ' .tiered-addon:checked').length > 0) {
		pdTierAddon = jQuery('#productContent_' + pid + ' .tiered-addon:checked').val();
	}
	
	var pdAddons = Array();
	if (jQuery('#productContent_' + pid + ' .addon:checked').length > 0) {
		for (var i=0; i<jQuery('#productContent_' + pid + ' .addon:checked').length; i++) {
			pdAddons.push(jQuery('#productContent_' + pid + ' .addon:checked').val());
		}
	}
	
	var pdBundle = '';
	if (jQuery('#productContent_' + pid + ' .bundle:checked').length > 0) {
		if (jQuery('#productContent_' + pid + ' .addon:checked').length > 0) {
			jQuery('#productContent_' + pid + ' .addon:checked').attr('checked', '');
		}
		if (jQuery('#productContent_' + pid + ' .tiered:checked').length > 0) {
			jQuery('#productContent_' + pid + ' .tiered:checked').attr('checked', '');
		}
		if (jQuery('#productContent_' + pid + ' .tiered-addon:checked').length > 0) {
			jQuery('#productContent_' + pid + ' .tiered-addon:checked').attr('checked', '');
		}
		var pdBundle = jQuery('#productContent_' + pid + ' .bundle:checked').val();
	}
	
	jQuery.post('/showcase/index/session/',
		{
			ajaxAction	: 'add',
			productId	: pid,
			tier		: pdTier,
			tierAddon	: pdTierAddon,
			addon		: pdAddons,
			bundle		: pdBundle
		},
		function(data) {
			
		}
	);
	
	jQuery(this).unbind('click');
	jQuery(this).attr('src','/showcase/images/layout/default/buttonAdd_inCart.png');
	jQuery(this).attr('width','102');
	jQuery(this).attr('height','23');
	jQuery(this).attr('alt','IN CART');
	jQuery(this).attr('title','IN CART');
	jQuery(this).removeClass('addButton');
	jQuery(this).addClass('inCart');
	jQuery(this).css('margin-top','2px');
	jQuery('#close_product_' + pid).unbind('click');
	jQuery('#close_product_' + pid).hide();

	addItem(pid, title) //UPDATE TOTAL
}

/** REMOVE FROM CART **/
function removeFromCart(e) {
	if(confirm('Are you sure you want to remove this product from your cart?')) {
		var id = jQuery(this).attr('id');
		id = id.replace('productRemove_','');
		var isOpen = jQuery('#productHeader_' + id);
		if(isOpen.length>0) { // Open
			shoppingCartLoader('show');
			var addButton = jQuery('#add_product_' + id);
			var productType = '';
			if(isOpen.hasClass('protectionItem')) {
				productType = 'protection';
			} else if(isOpen.hasClass('serviceItem')) {
				productType = 'service';
			} else if(isOpen.hasClass('productItem')) {
				productType = 'product';
			}
			
			jQuery(addButton).attr('src','/showcase/images/layout/default/buttons/btn_add_' + productType + '.gif');
			jQuery(addButton).attr('width','102');
			jQuery(addButton).attr('height','27');
			jQuery(addButton).attr('alt','ADD TO CART');
			jQuery(addButton).attr('title','ADD TO CART');
			jQuery(addButton).css('margin-top','0px');
			jQuery('#productContainer_' + id).remove();
			jQuery.post('/showcase/index/session/',
				{
					ajaxAction: 'remove',
					productId: id
				},
				function(data) {
					//if (jQuery.windstream.debug) {
					//	jQuery('#debugBox').prepend('Product ' + id + ' remove from cart sessioned.<br/>');
					//}
				}
			);
			jQuery(addButton).bind('click', addToCart);
			jQuery(addButton).removeClass('inCart');
			jQuery(addButton).addClass('addButton');
			
			var total = jQuery('#openProducts .itemHeader').length;
			if(total>1) {
				jQuery('#openProducts .closeButton').each(function(i) {
					var pid = this.id;
					var id = pid.replace('close_product_','');
					var inCart = jQuery('#productContainer_' + id);
					if(inCart.length==0) {
						jQuery(this).show();
						jQuery(this).bind('click', closeProduct);
					}
				});
			}
			//jQuery('#close_product_' + id).bind('click', closeProduct);
			//jQuery('#close_product_' + id).show();
			updateCart();
		}
	}
}

/*
 * Checkout
 */
/** Load checkout **/
function loadCheckout(e) {
	var cartHeight = jQuery('#shoppingCartContainer').height();
	jQuery('#contentContainer').hide();
	//jQuery('#checkoutProcess').height(cartHeight);
	jQuery('#checkoutProcess').addClass('loading');
	jQuery('#checkoutProcess').show();
	jQuery('.productCheckbox').hide();
	jQuery('#shoppingCartCheckout').hide();
	jQuery('#checkoutProcess').html('Loading...<br /><img src="/showcase/images/ajax-loader.gif" />');
	jQuery('#checkoutProcess').load('/showcase/checkout/', function() {
		jQuery(this).removeClass('loading');
		//jQuery('#checkoutContainer').height(cartHeight - 64);
		jQuery('#shoppingCartConfirmOrder').show();
		jQuery('#checkoutGoBack').bind('click', keepShopping);
		var order = '';
		jQuery('.productContainer').each(function(i) {
			var id = this.id.replace('productContainer_','');
			if(i==0) {
				order = id;
			} else {
				order = order + ',' + id;
			}
		});
		jQuery('#customer_order').val(order);
	});
}

/** Keep shopping **/
function keepShopping() {
	jQuery('#shoppingCartConfirmOrder').hide();
	jQuery('#shoppingCartCheckout').show();
	jQuery('#checkoutProcess').hide();
	jQuery('#contentContainer').show();
	jQuery('.productCheckbox').show();
}

/** Order Confirmation **/
function confirmOrder(e) {
	if(!jQuery.windstream.isProcessingOrder) {
		jQuery.windstream.isProcessingOrder = true;
		var options = {
			target: '#checkoutProcess',
			beforeSubmit: orderValidate,
			success: orderComplete
		};
		jQuery('#orderFormConfirmation').ajaxSubmit(options);
	}
	
	/*jQuery('#customer_first_name').qtip({
		content: 'Required!',
		style: {
			tip: 'leftMiddle',
			name: 'green'
		},
		position: {
			corner: {
				target: 'rightMiddle',
				tooltip: 'leftMiddle',
			}
		},
		show: {
			effect: { type: 'fade', length: 100},
			ready: true
		}
	});*/
}

function orderComplete(responseText, statusText) {
	jQuery('#checkoutProcess').removeClass('loading');
	// CLEAR SESSION!
	jQuery.post('/showcase/index/session/', { ajaxAction: 'clearsession' });
}

function orderValidate(formData, jqForm, options) {
	var valid = true;
	jQuery('#orderFormConfirmation .required').each(function(i) {
		if(jQuery(this).val()=='') {
			valid = false;
		}
	});
	
	if(valid) {
		var cartHeight = jQuery('#shoppingCartContainer').height();
		jQuery('#shoppingCartConfirmOrder').hide();
		jQuery('#contentContainer').hide();
		jQuery('#checkoutProcess').height(cartHeight);
		jQuery('#checkoutProcess').addClass('loading');
		jQuery('#checkoutProcess').html('Loading...<br /><img src="/showcase/images/ajax-loader.gif" />');
		return true;
	} else {
		alert('All fields are required!');
		jQuery.windstream.isProcessingOrder = false;
		return false;
	}
}

/**/
function aChange(e, ui) {
	var newId = ui.newHeader.attr('id');
	jQuery('#' + newId + ' .title').css('top','9px');
	jQuery('#' + newId + ' .ui-icon').css('top','2px');
	jQuery('#' + newId + ' .buttons').css('top','6px');
	var oldId = ui.oldHeader.attr('id');
	jQuery('#' + oldId + ' .title').css('top','11px');
	jQuery('#' + oldId + ' .ui-icon').css('top','4px');
	jQuery('#' + oldId + ' .buttons').css('top','8px');
	
	jQuery(ui.newContent.parent().get(0)).css('height', lastContentHeight);
	//setFrameHeight();
}