﻿//Removes <tr> when called from child of <td>/<th>
//Adds item back into the selector
//Only used when deleting is active
function removeRow(){
    var row = $(this).parent().parent();
    var table = row.parent().parent();
    var rowContents = row.contents();
    var desc = $(rowContents[0]).children().text();

    row.remove();
    
    //check the tboby to see if it has any rows in it
    //if it doesn't, hide it
	if ($('#current_cart tbody').contents().length === 0){
		table.hide('blind', {}, 500);
	    clearCart();
	}
	else {	
        getPricing();
        if ($('#confirmation_items_table').length == 0){
		    saveShoppingCart();
	    }
    }
    

    return false;
}

function removeRowByTarget(target){
	var row = $(target).parent().parent();
	var table = row.parent().parent();
    var rowContents = row.contents();
    var desc = $(rowContents[0]).children().text();

    row.remove();
       
    //check the tboby to see if it has any rows in it
    //if it doesn't, hide it
	if ($('#current_cart tbody').contents().length === 0){
		table.hide('blind', {}, 500);
		clearCart();
	}
	else {
	    if ($('#confirmation_items_table').length == 0){
		    saveShoppingCart();
	    }	
	}

    return false;
}

function updateTotal(){   
 
}

function registerClick(sku,name, price, giftCert, selectID, qty) {
    if (selectID !== null && selectID !== '') {
		$('#' + selectID).css('display', '');
	}
	
    $('#link' + sku).unbind("click");
    $('#link' + sku).click(function(e){
        e.stopPropagation();
		e.preventDefault();
		addToCart(sku,name, price,giftCert,selectID, qty);
    });
}

function addToCart(id, name, price, giftCert ,selectID, qty){
    $('#current_cart').show();
    var found = false;
    if (isNaN(price)) {
		price = 0;
	}
    
    if (selectID !== null && selectID !== '') {
		id = $('#' + selectID + ' option:selected').val();
		name += '<br/> (' + $('#' + selectID + ' option:selected').text() + ')';
		if (id == " ") {
			return false;
		}
    }
    
    if (giftCert !== null && giftCert !== '') {
		price = $('#' + giftCert).val();
		price = removeCurrency(price);
		
		if (isNaN(price) || parseFloat(price) === 0)
		{
			alert("Please enter a valid amount for the Gift Certificate.");
			return false;
		}
    }
    $('.numHidden').each(function(){
        if ($(this).attr('value') == id && $(this).parent('td').children('.numPrice').attr('value') == price && (giftCert === null || giftCert === ''))
        {
            found = true;   
            var qty = parseInt($(this).parent('td').children('#product_qty').val(),10) + 1;
            $(this).parent('td').children('#product_qty').val(qty);
            $(this).parent('td').children('.num').attr('value', qty);
            $(this).parent('td').children('.num').change(getPricing);
        }
    });

    if (found === false) {
        var htmlToAdd = "<tr class=\"room carpet cart_item\"><td style='padding-left: 5px;'><span>" + name;
        var max = 99;
        
        if (giftCert) {
            htmlToAdd += " ($" + parseFloat(price).toFixed(2) + ")</span><br/><span>To:</span><input type=\"text\" class=\"gift_to\" />";
            max = 1;
        } else {
			htmlToAdd += "</span>";
		}
		var disable = '';
		if (giftCert != '') {
		    disable = ' disabled = "false" ';
		}
        
        htmlToAdd += "</td><td class=\"room_quantity\">" + createQuantityDropdown(id, max, qty) + "<input type=\"hidden\" name=\"product_sku\" size=\"10\" maxlength=\"10\" class=\"numHidden\" value=\"" +id +"\"/><input type=\"hidden\" size=\"10\" maxlength=\"10\" class=\"numPrice\" value=\"" + price  + "\"/></td><td style='text-align:center;'><img class='trash_can' src='/Images/trashcan.gif' alt='Remove' title='Remove' ></td></tr>";
        
        $('#current_cart tbody').append(htmlToAdd);    
		$('.trash_can').unbind();
		$('.trash_can').click(removeRow);
		$('.gift_to').change(getPricing)
			.keypress(function(event) {
				if (event.keyCode == 13) {
					return false;
				};
		});
    }
    
    var GCAmt = removeCurrency($('.tbAmountGiftCert').val());

    $('.tbAmountGiftCert').val(addCurrency(GCAmt));
	getPricing();
	if ($('#confirmation_items_table').length == 0){
			        saveShoppingCart();
			    }
	resizeSidebar();	
	
	if ($.browser.safari === true){
		var height =  $('.tab-bg').height();
		$('.tab-bg').css('height', (height + 1) + 'px');
		$('.tab-bg').css('height', height + 'px');
	}
}

function createQuantityDropdown(name, max, selected){
    var html = "<select id='product_qty' onChange='getPricing();' class='quantitySelect qty" + name + "'>";
    
    for (var i = 0; i <= max; i++) {
        if (i != selected) {
            html += "<option value='" + i + "'>" + i + "</option>";
        } else {    
            html += "<option value='" + i + "' selected>" + i + "</option>";
        }
    }
    html += "</select>";
    
    return html;
}

function clearCart(){
    $('#quote_footer').hide();
    $('#current_cart').hide();
    $('#current_cart tbody').empty();
    $('#current_cart').hide();
    $('#quote_table').empty();
    $('#disable_panel').hide();
    $("#total_costs").hide();
    $("#total_costs_table").empty();
    $.cookie(SESSION_GUID, 'shopping_cart', null, { path: '/'});
    $('#quote_init').text("Select items and \"Add to Cart\"");
    $("#quote_init").show();
    return false;
}

function isNumberKey(evt){
	var charCode = evt.which ? evt.which : event.keyCode;
	if (charCode > 31 && (charCode < 48 || charCode > 57)) {
		return false;
	}
	if (charCode === 13){
		return false;
	}
	return true;
}

$(document).ready(function() {
	$('#quote_footer').hide();
	$('#current_cart').hide();
	$('#disable_panel').hide();
	$("#total_costs").hide();
	$('#order_disclaimer_detail').hide();
	$('.return_policy_link').click(function(e) {
		e.stopPropagation();
		e.preventDefault();
		$('#order_disclaimer_detail').fadeIn('slow');
		return false;
	});

	$('.num').blur(function(){
	    getPricing();	
	});

	$('#disclaimer_detail_close').click(function() {
		$('#order_disclaimer_detail').fadeOut('slow');
    });
    
    $('#go_to_checkout').click(checkout_redirect).parent().click(checkout_redirect);
    
    $('.tbAmountGiftCert').blur(function(){
		var val = $('.tbAmountGiftCert').val();
		val = val.replace(/\(|\)|\-/g, '');
		$('.tbAmountGiftCert').val(addCurrency(val));
	}).keypress(function(event) {
		if (event.keyCode == 13) {
			return false;
		}
	});

	$('.store_dd').each(function() {
		$(this).selectbox();
	});
	resetDropDownDimensions();

	if ($.cookie(SESSION_GUID, 'shopping_cart') !== null) {
		var sc = new ShoppingCart('shopping_cart');
		sc.Load();

		for (var i in sc.Items) {
			loadFromCookie(sc.Items[i].SKU, sc.Items[i].Name, sc.Items[i].Quantity, sc.Items[i].Price, sc.Items[i].GiftTo);
		}
		
		if (!/.*StoreOrderReview.aspx/.test(document.location)) {
		    getPricing();
		}
	}
	
	if (/.*Store.aspx/.test(document.location)) {
	    $('#continue_shopping_link').hide();
	}
	else {
	    $('#continue_shopping_link').show();
	}

	try {
		$('.store_item_div').each(function(e) {
			var image_width = $(this).find('.store_image').width();
			if (image_width < 170 && image_width != 0) {
				image_width = 170;
			}
			else if (image_width == 0) {
				image_width = 170;
				$(this).find('img').css('max-width', '170px');
			}
			else {
				if ($.browser.safari) {
					image_width = 170;
					$(this).find('img').width(170);
				}
			}

			var item_title = $(this).find('.store_item_data b').text();
			
			if (item_title.indexOf('Solution Kit') > -1) {
				image_width = 326;
				$(this).find('img').css('max-width', '');

				if ($.browser.safari) {
					$(this).find('img').width(326);
				}
			}

			var info_div_width = (630 - image_width) + 'px';
			image_width += 'px';
			$(this).find('.store_image_div').css('width', image_width).css('align', 'center');
			$(this).find('.store_info_div').css('width', info_div_width);

			resizeSidebar();
		});

		var GCAmt = removeCurrency($('.tbAmountGiftCert').val());
		
		if (parseFloat(GCAmt) < 0) {
			GCAmt = Math.abs(GCAmt);
		}

		$('.tbAmountGiftCert').val(addCurrency(GCAmt));
	}
	catch (ex) {

	}
	
	if ($.browser.safari) {
		$('.store_item_div .jquery-selectbox').width(154);
	}
	
	if ($.browser.msie && parseFloat($.browser.version) < 7) { 
		try {
		    $('#content_pane').css('width', '660px').css('margin', '-5px');
		    $('#store_content').css('padding', '5px 8px 0px 12px');
		} catch(ex){}
	}	
});
 
 function checkout_redirect(){
	if ($('#confirmation_items_table').length == 0){
				saveShoppingCart();
	}
	if(AjaxManager.Customer.getAccount() !== null){	
	    document.location = "/Home/Store/ChooseAddress.aspx";
	}
	else {
	    document.location = "/Home/Store/StoreLoginRegistration.aspx";
	}
	return false;
 }
 
 function resetDropDownDimensions() {
	$('.item-0').hide();
	$('.store_dd').each(function() {
		$(this).css('width', '273px');
	});
	$('.jquery-selectbox-list').each(function() {
		$(this).css('text-align','left');	
		$(this).css('width', '150px');
		$(this).css('height', '');
	});
}
 
function getPricing(){
	var products = []; 
	$('.room_quantity').each(function(){
		var getSKU = $(this).find('.numHidden').val();

	    if (parseInt($(this).find('.qty' + getSKU).val()) == 0) {
	        removeRowByTarget($(this).find('.qty' + getSKU));
	    } else {
		    var getQuantity = Math.abs(parseInt($(this).find('.qty' + getSKU).val(), 10));
		    var getPrice = $(this).find('.numPrice').val();
		    var sendTo = '';

		    try {
		        sendTo = $(this).parent().find('.gift_to').val().replace(/(<([^>]+)>)/g,"");
		        $(this).parent().find('.gift_to').val(sendTo);
		    } catch(ex) {
			    // do something
		    }
		    products.push(new Product(getSKU, getQuantity, getPrice, sendTo));
		}
	});
	if ($('#current_cart tbody').contents().length === 0) {
	    return;
	}
	var customer = {};		
	try{
		if (typeof($('#ship_first').val()) != "undefined") {
			customer.FirstName = $('#ship_first').val();
			customer.LastName = $('#ship_last').val();
			customer.Address1 =$('#ship_addr1').val();
			customer.Address2 = $('#ship_addr2').val();
			customer.Phone = $('#ship_phone').val();
			customer.City =  $('#ship_city').val();
			customer.State =  $('#ship_state').val();
			customer.Zip =  $('#ship_zip').val();	
		}
		else
		{
			throw(exception);
		}		
	    $.cookie(SESSION_GUID, 'shipTo', JSON.stringify(customer), {path: '/'});		
	}
	catch(ex){}
	
	if ($.cookie(SESSION_GUID, 'shipTo') != null){
	    customer = JSON.parse($.cookie(SESSION_GUID, 'shipTo'));
	}

		 var request = { products : products,
					 customer: customer};
	 $.ajax({
			url: '/Service.asmx/GetStorePricing',
			type: 'POST',
			datatype: 'json',
			data: JSON.stringify(request),
			timeout: 10000,
			contentType: 'application/json; charset=utf-8',
			success: function(res){
			    if ($('#confirmation_items_table').length == 0){
			        saveShoppingCart();
			    }
			    
				store_items = JSON.parse(res);			 
				$("#quote_init").hide();
				$("#total_costs_table").empty();
				$("#quote_table").empty();
				var subtotal = 0;
				for (var i = 0; i < store_items.SummaryInfoDetails.length; i ++)  {
					try{
						if (store_items.SummaryInfoDetails[i].ServiceTypeID != -1 && store_items.SummaryInfoDetails[i].ServiceTypeID != -2) {
							var nameItem = store_items.SummaryInfoDetails[i].Description;
							var qtyItem = store_items.SummaryInfoDetails[i].Quantity;
							var skuItem = store_items.SummaryInfoDetails[i].Product;
							var singleItem = 0;
							var itemPrice = store_items.SummaryInfoDetails[i].Amount;
							subtotal = subtotal + (itemPrice );
							$("#quote_table").append("<tr class='line_item'><td class='line_item_desc'><span style='margin-top:5px' id='product_desc'>" + nameItem + "</span>" +  
								"<td class='line_item_desc' style='width:9px'><span id='prod_qty'>" + qtyItem + "</span></td><td style='width:10px'>-</td><td class='line_item_value'>$<span id='prod_price'>" + itemPrice.toFixed(2) + "</span><input type='hidden' class='hiddenSKU' value='"+ skuItem + "' /></td></tr><tr><td><br/></td></tr>");
						} 
					} catch(ex) {
						// do something
					}
				}
			  
				$("#total_costs_table").show();
				$("#quote_footer").show();
				$("#quote_table").show();
			  
				if ($("#total_costs").css('display') === 'none'){
				    //this didn't work in safari or chrome
					//$("#total_costs").show('blind', {}, 500);
				    $("#total_costs").fadeIn("slow");
				}
				var total = 0;	
				$("#total_costs_table").append("<tr class='sub_total'><td class='sub_total_desc'>Subtotal:</td><td class='sub_total_value'>$" + subtotal.toFixed(2) +"</td></tr>");				
				var confirmationTableHtml = "<tr><td colspan=3></td><td class='confirmation_subtotal_desc'>Subtotal:</td><td class='confirmation_subtotal_value'>$" + subtotal.toFixed(2) + "</td></tr>";
				for (var i = 0; i < store_items.SummaryInfoDetails.length; i ++) {	
					try {
						if (store_items.SummaryInfoDetails[i].ServiceTypeID == -1) {
							$("#total_costs_table").append("<tr class='sub_total'><td class='sub_total_desc'>Tax:</td><td class='sub_total_value'>$" + store_items.SummaryInfoDetails[i].Amount.toFixed(2) +"</td></tr>");
							confirmationTableHtml += "<tr><td colspan=3></td><td class='confirmation_subtotal_desc'>Tax:</td><td class='confirmation_subtotal_value'>$" + store_items.SummaryInfoDetails[i].Amount.toFixed(2) + "</td></tr>";
							total = total + store_items.SummaryInfoDetails[i].Amount;
						} else if (store_items.SummaryInfoDetails[i].ServiceTypeID == -2) {
							$("#total_costs_table").append("<tr class=sub_total'><td class='sub_total_desc'>Shipping:</td><td class='sub_total_value'>$" + store_items.SummaryInfoDetails[i].Amount.toFixed(2) +"</td></tr>");
							confirmationTableHtml += "<tr><td colspan=3></td><td class='confirmation_subtotal_desc'>Shipping:</td><td class='confirmation_subtotal_value'>$" + store_items.SummaryInfoDetails[i].Amount.toFixed(2) + "</td></tr>";
							total = total + store_items.SummaryInfoDetails[i].Amount;
						}
					} catch(ex) {
						// do something
					}
					
					resizeSidebar();
				}
				
				total += subtotal;
				$("#total_costs_table").append("<tr class='total'><td class='total_desc'>Total:</td><td class='total_value'>$" + total.toFixed(2) +"</td></tr>");
				
				try {
					$('#updated_totals').empty();
					$('#updated_totals').append('<tr><td class="grid_2"></td></tr>');
					$('#updated_totals').append($('#total_costs_table').html());								
				} catch(ex) {				
					// do something
				}
				
				try{
					$('.line_item').each(function(){
							var desc = $(this).find('#product_desc').text();
							var sku = $(this).find('.hiddenSKU').val();
							var qty = $(this).find('#prod_qty').text();
							var price = $(this).find('#prod_price').text();
							var perItem = (parseFloat(price, 10) / qty).toFixed(2); 
							var htmlToAdd = "<tr class=\"confirm_item\" style=\"font-weight:normal\"><td class=\"confirm_table_cell\" style=\"text-align:left;\">" + sku + "</td><td class=\"confirm_table_cell\" style=\"text-align:left\">" + desc + "</td><td class=\"confirm_table_cell\" style=\"text-align:right;\">$"+ perItem + "</td><td class=\"confirm_table_cell\" style=\"text-align:center;\">" + qty + "</td><td class=\"confirm_table_cell\" style=\"text-align:right;\">$" + price + "</td></tr>";
							$('#item_table tbody').append(htmlToAdd);
					});
					
					$('#item_table tbody').append(confirmationTableHtml);	
                    $('#item_table tbody').append("<tr><td colspan=3></td><td class='confirmation_subtotal_desc'>Total:</td><td class='confirmation_subtotal_value' style='font-weight: bold;'>$" + total.toFixed(2) + "</td></tr>");

					$('#order_total').append($('#total_costs_table .total .total_value').text()); 
							resizeSidebar();
				} catch(ex) {
				throw ex;
				}

                
//                if (/.*Store.aspx/.test(document.location))
//                {
//                    //From StoreCheckout.js it is only availiable at confirm page.
//                    setLineItems();
//                }
                
				// send the email confirmation if the order was submitted; we do it here because the list of items needs to have been rendered first
				if ($('#hiddenStoreConfirmFields').length == 1) {
	                execute_confirmation();
	            }
	            
	            
			},
			error: function(res){
				display_error_message();
			}
			
		});	
	if ($.browser.safari === true){
		var height =  $('.tab-bg').height();
		$('.tab-bg').css('height', (height + 1) + 'px');
		$('.tab-bg').css('height', height + 'px');
    }
    return true;
}
 
function display_error_message(){
	$("#quote_init").hide();
	$("#quote_table").empty();
	$("#quote_table").append("<tr class=\"line_item\"><td class=\"line_item_desc red\">We are currently experiencing technical difficulties.  Pricing for store purchases is unavailable.  We apologize for any inconvenience.</td></tr>");
}

function removeCurrency( strValue ) {
  var objRegExp = /\(/;
  var strMinus = '';

  //check if negative
  if(objRegExp.test(strValue)){
    strMinus = '-';
  }

  objRegExp = /\)|\(|[,]/g;
  strValue = strValue.replace(objRegExp,'');
  if(strValue.indexOf('$') >= 0){
    strValue = strValue.substring(1, strValue.length);
  }
  return strMinus + strValue;
}

function addCommas( strValue ) {
  var objRegExp  = new RegExp('(-?[0-9]+)([0-9]{3})');

    //check for match to search criteria
    while(objRegExp.test(strValue)) {
       //replace original string with first group match,
       //a comma, then second group match
       strValue = strValue.replace(objRegExp, '$1,$2');
    }
  return strValue;
}

function addCurrency( strValue ) {
  var objRegExp = /-?[0-9]+\.[0-9]{2}$/;
  strValue = strValue.replace(/\$/g, ''); 

    if( objRegExp.test(strValue)) {
		objRegExp.compile('^-');
		strValue = addCommas(strValue);
		
		if (objRegExp.test(strValue)){
			strValue = '(' + strValue.replace(objRegExp,'') + ')';
		}
		
		return '$' + strValue;
    } else {
		return strValue;
	}
}

function ShoppingCart(cookie_name){
	this.$name = cookie_name;
	this.Items = {};
}

function StoreItem(name, productSku,qty, price,giftTo){
	this.Name = name;
	this.SKU = productSku;
	this.Quantity = qty;
	this.Price = price;
	this.GiftTo = giftTo;
}

function saveShoppingCart(){
	var	status = new ShoppingCart('shopping_cart');
	var _items = scanTable('current_cart tbody');	
	for (var i in _items) {
		var _item = _items[i];

		if (_item.SKU === 'Gift'){
			status.Items[_item.SKU + '-' + i] = _item;
		} else {
			status.Items[_item.SKU] = _item;
		}
	}
	status.Save();
	return status;
}

function scanTable(tableID){
	var table = $('#' + tableID);
	var rows = table.children();
	var tableContents = [];
	
	var tds;
    
	for (var j = 0; j < rows.length; j++) {		
		tds = rows.eq(j).children();
		var rowContents = new StoreItem(
								tds.eq(0).children().eq(0).text(),
								tds.eq(1).children().eq(1).val(),
								tds.eq(1).children().eq(0).val(),
								tds.eq(1).children().eq(2).val(),
								tds.eq(0).find('.gift_to').val()
							);
		tableContents.push(rowContents);	
	}	
	return tableContents;
}

ShoppingCart.prototype.Save = function() {
	this.ErrorMessage = undefined;
	$.cookie(SESSION_GUID, this.$name, this.toJsonString(), { path: '/'});
};

ShoppingCart.prototype.toJsonString = function() {
	//this.$document = null;
	var s = JSON.stringify(this);
	
	return s;
};

ShoppingCart.prototype.Load = function(){
	var json_string = $.cookie(SESSION_GUID, this.$name);
	if (json_string !== null) {
		var cleaning_info = JSON.parse(json_string);
		this.Items = cleaning_info['Items'];	
	}
};

function loadFromCookie(id,name, qty, price, giftTo){
    $('#current_cart').show();
    var found = false;
    var htmlToAdd = "<tr class='room carpet cart_item'><td><span style='padding-left: 5px'>" + name + "</span>";
    var max = 99;
    
    if (id == "Gift") {
		htmlToAdd += "<br/><span>To:</span><input type='text' class='gift_to' value=\"" + giftTo + "\"/>";
		max = 1;
    } else {
		htmlToAdd += "</span>";
    }
    
    htmlToAdd += "</td><td class='room_quantity'>" + createQuantityDropdown(id, max, qty) + "<input type='hidden' name='product_sku' size='10' maxlength='10' class='numHidden' value='" +id +"'/><input type='hidden' size='10' maxlength='10' class='numPrice' value='" + price  + "'/></td><td style='text-align:center;'><img class='trash_can' src='/Images/trashcan.gif' alt='Remove' title='Remove' ></td></tr>";
    $('#current_cart tbody').append(htmlToAdd);    
	$('.trash_can').unbind();
	$('.trash_can').click(removeRow);
}

Product.prototype.toJsonString = function() {
	var s = JSON.stringify(this);
	
	return s;
};

function Product(sku, qty, price, giftTo){
	this.ProductSKU = sku; 
	this.Quantity = qty;
	this.Price = price;
	this.GiftTo = giftTo;
}