/**
 * Custom JS Functions
 */
 
// ** global variables ** //

/**
 * Product Browse dattributeid
 */
var pbDid = 405307;

/**
 * Attribute Search dattributeid
 */
var asDid = 405308;

/**
 * Create a shortcut to jQuery, calling no conflict due to our custom $ function
 * {@link http://docs.jquery.com/Using_jQuery_with_Other_Libraries}
 */
var $j = jQuery.noConflict();

/**
 * Function used to display product selected by
 * user from our product browse list
 * @param {int} did
 * @param {string} siteurl
 * @param {object} product_data
 * @return {string} prod_div
 */
function show_product(did, siteurl, product_data) {
	if (product_data == "") {
		alert("No data available for the selected product. Please try your request again.");
		product_browse('');
		return;
	}
	
	//set our product_data (parsing our JSON string)
	var product_data = json_decode(unescape(product_data));
	
	//begin our product listing
	var prod_div = ' <div class="box rollover">';
	
	//product image	
	if (product_data.productImage != '' && product_data.productImage != 'null') {
		prod_div += '  <img class="thumbnail float-left" alt="product image" src="' + siteurl + 'content/products/images/thumb/' + product_data.productImage + '" />';
	}

	prod_div += '  <div class="box-text float-left">';
	//product name	
	if (product_data.realProductName != 'null') {
		prod_div += '  <h3>' + product_data.realProductName + '</h3>'; 
	}

	//subtitle
	if (product_data.subtitle != 'null') {
		prod_div += '  <h4>' + product_data.subtitle + '</h4>'; 
	}

	//description
	if (product_data.productDescription != 'null') {
		prod_div += '  <p>' + product_data.productDescription + '</p>';
	}
	
	prod_div += '  <div class="clear"></div>';
	
	//end of content div
	prod_div += '  </div>';
	prod_div += '  <div class="clear"></div>';
	prod_div += ' </div>';

	return prod_div;	
}

//-- INVERTER SELECTION --//

/**
 * Function used to reset our inverter choices form
 * @param {boolean} clear_wattage
 */
function reset_inverter_choices_form(clear_phase) {
	var input_ref = $('input'), output_ref = $('output'), conductors_ref = $('conductors'), wattage_ref = $('wattage');
	
	remove_all_options(input_ref);
	remove_all_options(output_ref);
	remove_all_options(conductors_ref);
	remove_all_options(wattage_ref);
	
	//disable our select menus
	input_ref.disabled = "disabled";
	output_ref.disabled = "disabled";
	conductors_ref.disabled = "disabled";
	wattage_ref.disabled = "disabled";
			
	$('inverter-choice-results').innerHTML = '';

	if (clear_phase) {
		$('phase').selectedIndex = 0;
	}
}

/**
 * Function used to get input voltage for selected wattage
 */
function get_inverter_input() {
	wattage = $('wattage').value;
	phase = $('phase').value;
	conductors = $('conductors').value;
	
	//reset to previous step
	remove_all_options('input');
	remove_all_options('output');
	$('output').disabled = "disabled";

	if (wattage != '') {		
		var failure = function(t) {alert('Unable to retrieve input voltages for selected wattage.');}
		var success = function(t) {
				if (t.responseText == '') {
					alert('Unable to retrieve input voltages for selected wattage.');
				} else {
					var input_options = json_decode(t.responseText), input_ref = $('input');

					input_ref.removeAttribute('disabled');
					
					for (var i = 0, count = input_options.length; i < count; i++) {
						opt = new Option(input_options[i].input, input_options[i].input);
						add_option(input_ref, opt);
					}
					
					toggle_element('loading');
				}
		}
		
		var parameters = new Object();
		parameters._method = 'get_inverter_input';
		parameters.wattage = wattage;
		parameters.phase = phase;
		parameters.conductors = conductors;
		
		AjaxRequest.post({
				'url': 'includes/ajax.php',
				'parameters': parameters,
				'onLoading': toggle_element('loading'),
				'onSuccess': success,
				'onError': failure
		});
	}//if (wattage != '')
}

/**
 * Function used to get output voltage for 
 * selected wattage and input voltage
 */
function get_inverter_output() {
	wattage = $('wattage').value;
	input = $('input').value;
	phase = $('phase').value;
	conductors = $('conductors').value;
	
	//reset to previous step
	remove_all_options('output');
	$('output').removeAttribute('disabled');
	$('inverter-choice-results').innerHTML = '';
	
	if (wattage != '' && input != '') {
		var failure = function(t) {alert('Unable to retrieve output voltages for selected wattage.');}
		var success = function(t) {
				if (t.responseText == '') {
					alert('Unable to retrieve output voltages for selected wattage.');
				} else {
					var output_options = json_decode(t.responseText), output_ref = $('output');
					
					for (var i = 0, count = output_options.length; i < count; i++) {
						opt = new Option(output_options[i].output, output_options[i].output);
						add_option(output_ref, opt);
					}
					
					output_ref.removeAttribute('disabled');
					toggle_element('loading');
				}
		}
		
		var parameters = new Object();
		parameters._method = 'get_inverter_output';
		parameters.wattage = wattage;
		parameters.input = input;
		parameters.phase = phase;
		parameters.conductors = conductors;

		AjaxRequest.post({
				'url': 'includes/ajax.php',
				'parameters': parameters,
				'onLoading': toggle_element('loading'),
				'onSuccess': success,
				'onError': failure
		});
	}//if (wattage != '' && input != '')
}

/**
 * Function used to get inverter choice for
 * selected wattage, input voltage, and output voltage
 */
function get_inverter_choice() {
	wattage = $('wattage').value;
	input = $('input').value;
	phase = $('phase').value;
	conductors = $('conductors').value;
	output = $('output').value;
	inverter_results_ref = $('inverter-choice-results');
	inverter_results_ref.innerHTML = '';

	if (wattage != '' && input != '' && output != '') {
		var failure = function(t) {alert('Unable to retrieve a central lighting inverter based on the selected search criteria.');}
		var success = function(t) {
				if (t.responseText == '') {
					alert('Unable to retrieve a central lighting inverter based on the selected search criteria.');
				} else {
					var inverter_choice = json_decode(t.responseText);
					
					for (var i = 0, count = inverter_choice.length; i < count; i++) {
						inverter_results_ref.innerHTML += '<div class="box">' +
														 ' <h4>' + inverter_choice[i].answer + '</h4>' +
														 ' <p>' + inverter_choice[i].description + '<br />' +
														 '<a href="' + inverter_choice[i].product_url + '">For more information, click here</a></p>' +
														 '</div>';
					}
					toggle_element('loading');
				}
		}
		
/*
var wattage_options = json_decode(t.responseText), wattage_ref = $('wattage');
					
					for (var i = 0, count = wattage_options.length; i < count; i++) {
						opt = new Option(wattage_options[i].wattage, wattage_options[i].wattage);
						add_option(wattage_ref, opt);
					}
					
					*/
					
		var parameters = new Object();
		parameters._method = 'get_inverter_choice';
		parameters.wattage = wattage;
		parameters.input = input;
		parameters.output = output;
		parameters.phase = phase;
		parameters.conductors = conductors;

		AjaxRequest.post({
				'url': 'includes/ajax.php',
				'parameters': parameters,
				'onLoading': toggle_element('loading'),
				'onSuccess': success,
				'onError': failure
		});		
	}//if (wattage != '' && input != '' && output != '')
}

/**
 * Function used to get conductors for selected inverter phase
 */
function get_inverter_conductors() {
	phase = $('phase').value;
	reset_inverter_choices_form(false);

	if (phase == 'three-phase') {		
		var failure = function(t) {alert('Unable to retrieve conductors for selected inverter type.');}
		var success = function(t) {
				if (t.responseText == '') {
					alert('Unable to retrieve conductors for selected inverter type.');
				} else {
					var conductor_options = json_decode(t.responseText), conductor_ref = $('conductors');

					conductor_ref.removeAttribute('disabled');
					
					for (var i = 0, count = conductor_options.length; i < count; i++) {
						opt = new Option(conductor_options[i].conductors, conductor_options[i].conductors);
						add_option(conductor_ref, opt);
					}
					
					toggle_element('loading');
				}
		}
		
		var parameters = new Object();
		parameters._method = 'get_inverter_conductors';
		parameters.phase = phase;
		
		AjaxRequest.post({
				'url': 'includes/ajax.php',
				'parameters': parameters,
				'onLoading': toggle_element('loading'),
				'onSuccess': success,
				'onError': failure
		});
	} else if (phase == 'single-phase') {
		//single-phase doesn't have conductors
		get_inverter_wattage();
	} //if (phase != 'single-phase')
}

/**
 * Function used to get wattage for 
 * selected phase and conductors
 */
function get_inverter_wattage() {
	phase = $('phase').value;
	conductors = $('conductors').value;
	
	//reset to previous step
	remove_all_options('wattage');
	$('wattage').removeAttribute('disabled');
	remove_all_options('input');
	$('input').disabled = "disabled";
	remove_all_options('output');
	$('output').disabled = "disabled";
	
	$('inverter-choice-results').innerHTML = '';
	
	if (phase != '') {
		var failure = function(t) {alert('Unable to retrieve wattage for selected inverter type and conductors.');}
		var success = function(t) {
				if (t.responseText == '') {
					alert('Unable to retrieve wattage for selected inverter type and conductors.');
				} else {
					var wattage_options = json_decode(t.responseText), wattage_ref = $('wattage');
					
					for (var i = 0, count = wattage_options.length; i < count; i++) {
						opt = new Option(wattage_options[i].wattage, wattage_options[i].wattage);
						add_option(wattage_ref, opt);
					}
					
					wattage_ref.removeAttribute('disabled');
					toggle_element('loading');
				}
		}
		
		var parameters = new Object();
		parameters._method = 'get_inverter_wattage';
		parameters.phase = phase;
		parameters.conductors = conductors;
		
		AjaxRequest.post({
				'url': 'includes/ajax.php',
				'parameters': parameters,
				'onLoading': toggle_element('loading'),
				'onSuccess': success,
				'onError': failure
		});
	}//if (wattage != '' && input != '')
}



//-- REPLACEMENT PARTS --//

/**
 * Function used to validate our replacement parts
 * search form and submit to our ajax call
 * @param {object} the_form
 * @param {boolean} show_price_column
 * @returns {boolean}
 */
function validate_replacement_parts_form(the_form, show_price_column) {
	//at least one search criteria is required
	var model = $('model').value, part_number = $('part_number').value, part_description = $('part_description').value;
	
	if (model == '' && part_number == '' && part_description == '') {
		alert('At least one search criteria is required.');
	} else {
		var failure = function(t) {alert('Unable to retrieve replacement parts for entered search criteria.');}
		var success = function(t) {
				if (t.responseText == '') {
					alert('Unable to retrieve replacement parts for entered search criteria.');
				} else {
					$('replacement-parts-results').innerHTML = t.responseText;
					toggle_element('loading');
				}
		}
		
		var parameters = new Object();
		parameters._method = 'get_replacement_parts';
		parameters.model = model;
		parameters.part_number = part_number;
		parameters.part_description = part_description;
		parameters.show_price_column = show_price_column;

		AjaxRequest.post({
				'url': 'includes/ajax.php',
				'parameters': parameters,
				'onLoading': toggle_element('loading'),
				'onSuccess': success,
				'onError': failure
		});		
	}

	return false;
}

//-- QUICK SEARCH FUNCTIONS --//

function show_search_results(start, end) {
	var str_html = '';
	
	for (var i = start; i < end; i++) {
		str_html += '<div class="box">';
		str_html += '<img class="thumbnail float-left" src="content/products/' + results[i].productImage + '" alt="' + results[i].productName + '" />';
		str_html += '<div class="box-text float-left">';
		str_html += '<h3>' + results[i].productName + '</h3>';
		str_html += '<h4>' + results[i].subtitle + '</h3>';
		str_html += '<p>' + results[i].productDescription + '</p>';
		str_html += '<p><a href="' + results[i].filename + '">View Product Page</a></p>';
		str_html += '</div>';
		str_html += '<div class="clear"></div>';
		str_html += '</div>';
	}
	
	$('search-contents').innerHTML = str_html;	
}

/**
 * Function used to write out our product browse category list
 * @param {int} did
 * @param {string} divid
 * @param {string} siteurl
 * @param {string} selected_did Optional
 */
function write_product_browse_dd(did, divid, siteurl, selected_did) {
	if (!selected_did) {var selected_did = '';}		
	var nextdiv = next_div('prod-browse', divid);
			 
	var categories = '<br />';
	
	var choices = list_children(did, 'pb');
		
	for (var i = 0, c_count = choices.length; i < c_count; i++) {
		var var_object = new Object();
			var_object.category = choices[i];
			var_object.siteurl = siteurl;
			
		categories += '<div id="prod-browse-button-' + choices[i] + '" class="accordion-button" onclick="show_product_browse_list(\'' + escape(json_encode(var_object)) + '\');"><span class="light">' + PBindex[choices[i]][1] + '</span></div>\n' +
		              '<div id="prod-browse-content-' + choices[i] + '" class="accordion-content"><div class="clear"></div></div>\n';
	}

	categories += '<div id="' + nextdiv + '"></div>';
	$(divid).innerHTML = categories;
	
	if (selected_did != '') {
		//here we need to get our product list for this category
		var parameters = new Object();
			parameters._method = 'get_index_product_list';
			parameters.did = selected_did;
		
			AjaxRequest.post({
				'url': siteurl + 'includes/ajax.php',
				'parameters': parameters,
				'onLoading': toggle_element('loading'),
				'onSuccess': function(t) {write_product_browse_list(selected_did, siteurl, t.responseText);toggle_element('loading');},
				'onError': function(t) {alert('Unable to retrieve product(s) for this product type');toggle_element('loading');}
			});
	}
}


/**
 * Function used to process our product browse
 * list item rollover functionality
 * @param {object} select_ref
 * @param {string} divid
 * @param {string} type
 * @param {string} siteurl
 * @param {string} attribute_search_history Optional
 */
function search_product_browse(category,siteurl) {
	//don't process if they selected the top select list item ('all')
	if (category == pbDid) {		
		$('prod-browse-content-' + category).innerHTML = '';
	} else {
		//reset our div
		$('prod-browse-content-' + category).innerHTML = '';

		//if this is a non-product link, open a new window with our url
		if (PBindex[category][0] == "Non-Product Link") {
			//reset our category list?
			//open our window
			window.open(PBindex[category][2]);					
			return;
		} else {
			var parameters = new Object();
				parameters._method = 'get_index_product_list';
				parameters.did = category;
			
				AjaxRequest.post({
						'url': siteurl + 'includes/ajax.php',
						'parameters': parameters,
						'onLoading': toggle_element('loading'),
						'onSuccess': function(t) {write_product_browse_list(category, siteurl, t.responseText);toggle_element('loading');},
						'onError': function(t) {alert('Unable to retrieve product(s) for this product type');toggle_element('loading');}
				});
		}
	}
}

/**
 * Function used to write out our product browse list
 * @param {int} did
 * @param {string} divid
 * @param {string} siteurl
 * @param {object} product_data
 */
function write_product_browse_list(did, siteurl, product_data) {
	var filename_array = window.location.pathname.split('/');	
	var filename = filename_array[filename_array.length-2];

	var prod_list = "<ul id=\"" + did + "\" class=\"side-nav\" style=\"width:180px\">\n";
    
	if (product_data == "") {
		alert("No data available for the selected category. Please try your request again.");
		product_browse('');
		return;
	}

	//parse our json string
	product_data = json_decode(product_data);
	var products = product_data.products;
		
	for (var i = 0, product_count = products.length; i < product_count; i++) {
		if (filename == products[i].filename) {//on this product page, don't link and no mouseover event
			prod_list += '<li><a class=\"current\">' + products[i].productName + '</a></li>\n';
		} else {//not on product page, include mouseover and link
			prod_list += '<li><a href="' + siteurl + 'products/' + products[i].filename + '/?pbid=' + did + '">' + products[i].productName + '</a>' +
						 ' <ul>' +
						 '  <li>' + show_product(products[i].did, siteurl, json_encode(products[i])) + '</li>' +
						 ' </ul>' +
						 '</li>';
		}
	}
	
	prod_list += "</ul>\n<div class=\"clear\"></div>";

	$('prod-browse-content-' + did).innerHTML = prod_list;
	
	//now we need to run our script to build our sub menus
	buildsubmenus(did);
	
	//if our menu is open, we're going to close it, else open it
	if ($j('#prod-browse-content-' + did).is(':visible')) {
		$j('#prod-browse-content-' + did).slideUp('normal');
	} else {
		$j('#prod-browse-content-' + did).slideDown('normal');
	}
}

/**
 * Function used to initialize our product browse functionality
 * @return string|int selected_did Optional
 */
function product_browse(selected_did) {
	//closes all accordion content divs
	$j("div.accordion-content").hide();
	
	if (!selected_did) {var selected_did = '';}	
	var siteurl = '' 

	$('content-browse').style.display = '';
	$('content').style.display = 'block';

	var ulstring = ' <ul>' +
				   '  <li><a href="javascript: void(0);" onclick="attribute_search();' + ((typeof(pageTracker) != 'undefined') ? 'pageTracker._trackPageview(\'/attribute_search/\');' : '') + '"><span>Attribute Search</span></a></li>' +
				   '  <li class="selected"><a href="javascript: void(0);" onclick="product_browse();' + ((typeof(pageTracker) != 'undefined') ? 'pageTracker._trackPageview(\'/product_browse/\');' : '') + '"><span>Product Browse</span></a></li>' +
				   ' </ul>' +
				   ' <div class="clear"></div>';

	$('pbrowse-tabs').innerHTML = ulstring;	
	$('content-browse').innerHTML = '';
	$('bottomDiv').innerHTML = '';
	$('attSearch1').innerHTML = ''; 
	$('prod-browse').innerHTML = '';
	$('attSearch1').style.display = 'none';

	write_product_browse_dd(pbDid, 'prod-browse', siteurl, (selected_did != '' ? selected_did : ''));
	
	$('prod-browse').style.display = '';
}

/**
 * Simple accordian style menu, for use with dual-lite product browse
 * @param string param_object
 * Original code taken from {@link http://www.stemkoski.com/stupid-simple-jquery-accordion-menu/} 
 */
function show_product_browse_list(param_object) {
	$j('div.accordion-content').slideUp('normal');

	//set our param object for passing variables into our search product browse function
	var object = json_decode(unescape(param_object));
	
	//execute our search product browse function
	search_product_browse(object.category, object.siteurl);
}

/**
 * Function used to build our submenus for our
 * product browse navigation menu
 * @param {string} menu_id
 * Original Code taken from {@link http://www.dynamicdrive.com/style/csslibrary/item/suckertree-menu-vertical/}
 */
function buildsubmenus(menu_id){
	var ultags = $(menu_id).getElementsByTagName('ul');
	
	for (var t = 0; t < ultags.length; t++) {
		if (ultags[t].parentNode.parentNode.id == menu_id) //if this is a first level submenu
			ultags[t].style.left=ultags[t].parentNode.offsetWidth + 'px'; //dynamically position first level submenus to be width of main menu item
		else //else if this is a sub level submenu (ul)
			ultags[t].style.left = ultags[t-1].getElementsByTagName('a')[0].offsetWidth + 'px'; //position menu to the right of menu item that activated it
			ultags[t].parentNode.onmouseover = function() {
				this.getElementsByTagName("ul")[0].style.display = 'block'
			}
		
		ultags[t].parentNode.onmouseout = function() {
			this.getElementsByTagName('ul')[0].style.display = 'none';
		}
	}
	
	for (var t = ultags.length-1; t >-1; t--) { //loop through all sub menus again, and use "display:none" to hide menus (to prevent possible page scrollbars
		ultags[t].style.visibility = 'visible';
		ultags[t].style.display = 'none';
	}
}

/**
 * Function to initialize our attribute search functionality
 * @param {string} attribute_search_history Optional
 */
function attribute_search(attribute_search_history) {
	if (!attribute_search_history) {var attribute_search_history = '';}
	var siteurl = ''; 
	
	$('content-browse').style.display = 'none';
	$('content').style.display = 'block';
				   
	var ulstring = ' <ul>' +
				   '  <li class="selected"><a href="javascript: void(0);" onclick="attribute_search();' + ((typeof(pageTracker) != 'undefined') ? 'pageTracker._trackPageview(\'/attribute_search/\');' : '') + '"><span>Attribute Search</span></a></li>' +
				   '  <li><a href="javascript: void(0);" onclick="product_browse();' + ((typeof(pageTracker) != 'undefined') ? 'pageTracker._trackPageview(\'/product_browse/\');' : '') + '"><span>Product Browse</span></a></li>' +
				   ' </ul>';

	$('pbrowse-tabs').innerHTML = ulstring;

	$('content-browse').innerHTML = '';
	$('attSearch1').innerHTML = ''; //clear existing att search
	
	$('content-browse').style.display = 'none';
	$('attSearch1').style.display = 'block';
	$("prod-browse").innerHTML = ''; //clear any existing product list
	$("prod-browse").style.display = 'none';

	if (attribute_search_history != '') {
		write_attribute_search_dd(asDid, 'attSearch1', siteurl, attribute_search_history, attribute_search_history);
	} else {
		write_attribute_search_dd(asDid, 'attSearch1', siteurl);
	}
}

//-- FILE SEARCH FUNCTIONS --//

/**
 * Function used to show our given div, also hides
 * other divs and sets active nav link (used by our
 * download pages e.g. instruction sheets, photomotry, etc.)
 * @param {string} div
 */
function show_div(div) {
	var nav_array = $('products-nav').getElementsByTagName('a'), div_array = $('products-container').getElementsByTagName('div');

	//reset our other nav links
	for (var i = 0, nav_length = nav_array.length; i < nav_length; i++) {
		nav_array[i].className = '';
	}

	//hide all our other divs
	for (i = 0, div_length = div_array.length; i < div_length; i++) {
		if (div_array[i].id != '') {
			div_array[i].style.display = "none";
		}
	}

	//clear out our file-search-results (where applicable)
	if ($('file-search-results')) {
		$('keywords').value = '';
		$('file-search-results').innerHTML = '';
		$('file-search-results').style.display = "none";
	}
	
	//attempt to show our div and set our current link
	if ($(div)) {
		//set our active nav link
		$('nav-' + div).className = "current";

		//show our div
		$(div).style.display = "block";
	}

	return;
}

/**
 * Function used to search our files, based on the entered keyword(s)
 * @param {string} filetype
 */
function search_files(filetype) {
	var nav_array = $('products-nav').getElementsByTagName('a'), div_array = $('products-container').getElementsByTagName('div'), keywords = $('keywords').value;

	//reset our other nav links
	for (var i = 0, nav_length = nav_array.length; i < nav_length; i++) {
		nav_array[i].className = '';
	}

	//hide all our other divs
	for (i = 0, div_length = div_array.length; i < div_length; i++) {
		if (div_array[i].id != '') {
			div_array[i].style.display = "none";
		}
	}
	
	if (keywords != '' && filetype != '') {
		var failure = function(t) {alert('Unable to process your search.');toggle_element('loading');}
		var success = function(t) {$('file-search-results').innerHTML = (t.responseText == '') ? 'No results found for ' + keywords + '.' : t.responseText;toggle_element('loading');}

		var parameters = new Object();
		parameters._method = 'search_files';
		parameters.filetype = filetype;
		parameters.keywords = keywords;
		
		AjaxRequest.post({
				'url': 'includes/ajax.php',
				'parameters': parameters,
				'onLoading': toggle_element('loading'),
				'onSuccess': success,
				'onError': failure
		});
	}
}

//-- SHOPPING CART FUNCTIONS --//

/**
 * Function used to add/update item in shopping cart. Checks to ensure
 * item isn't already in the cart, if so update routine runs
 * @param {integer} item_id
 */
function add_to_cart(item_id) {
	var total_items = $('total_items').value;
	var new_item_id = (parseInt(total_items) + 1);
	var item_name = ($('product_name_' + item_id) ? $('product_name_' + item_id).innerHTML : '');
	var item_number = ($('product_number_' + item_id) ? $('product_number_' + item_id).innerHTML : '');
	var item_description = $('product_description_' + item_id).innerHTML;
	var item_quantity = $('product_quantity_' + item_id).value;
	var item_price = ($('product_price_' + item_id).value / 100);
	var item_size = ($('product_size_' + item_id) ? $('product_size_' + item_id).value : '');

	if (item_quantity == '') {
		alert('Please enter a quantity for item: ' + item_name);
		return;
	}

	if ($('item_id_' + item_id + (item_size != '' ? '_' + item_size : ''))) {
		//item exists in cart already, update
		update_cart(item_id, $('item_id_' + item_id + (item_size != '' ? '_' + item_size : '')).value, item_quantity);
	} else {
		//item doesn't exist, add
		var row = build_shopping_cart_row(new_item_id, item_id, item_quantity, item_price, item_name, item_number, item_description, item_size);
		var target_element = $(total_items == 0 ? 'cart_header' : 'cart_item_' + total_items); //determine where to add
		var next = target_element.nextSibling;
		(next) ? target_element.parentNode.insertBefore(row, next) : target_element.parentNode.appendChild(row);
	
		//update total items in cart
		$('total_items').value = (parseInt(total_items)+parseInt(1));
		
		//update cart subtotal
		update_cart_subtotal();
	}

	//clear out our quantity
	$('product_quantity_' + item_id).value = '';

	//reset our size if applicable
	if (item_size != '') {
			$('product_size_' + item_id).selectedIndex = 0;
	}

	//scroll to our shopping cart details
	$j.scrollTo('#cart-details', 700);
}

/**
 * Function to build our elements for a new shopping cart row
 * @param {integer} new_item_id
 * @param {integer} item_id
 * @param {integer} item_quantity
 * @param {string} item_price
 * @param {string} item_name Optional
 * @param {string} item_number Optional
 * @param {string} item_description
 * @param {string} item_size
 * @return {object} row
 */
function build_shopping_cart_row(new_item_id, item_id, item_quantity, item_price, item_name, item_number, item_description, item_size) {
	//Robin: "Holy Shit Batman! All this just to build our table row client side!!!"
	var row = '';
	var cell = '';
	var attribute = '';
	var link_node = '';
	var input = '';
	var image = '';
	row = document.createElement('tr');
	row.setAttribute('id', 'cart_item_' + new_item_id);
	row.setAttribute('class', 'cart-content');

	cell = document.createElement('td');
	cell.setAttribute('height', '30');

	link_node = document.createElement('a');
	link_node.setAttribute('href', 'javascript:void(0);');				
	link_node.setAttribute('onclick', "$j.scrollTo('#product_" + item_id + "', 700);");
	link_node.appendChild(document.createTextNode(((item_number != '') ? item_number + ' - ' + ((item_name != '') ? item_name : item_description) : '') + ((item_size != '') ? ' (' + item_size + ')' : '')));
	cell.appendChild(link_node);
	row.appendChild(cell);

	cell = document.createElement('td');
	cell.setAttribute('align', 'left');
	cell.setAttribute('height', '30');
	cell.appendChild(document.createTextNode(format_currency(item_price)));
	row.appendChild(cell);

	cell = document.createElement('td');
	cell.setAttribute('height', '30');

	input = document.createElement('input');
	input.setAttribute('type', 'hidden');
	input.setAttribute('id', 'item_id_' + item_id + (item_size != '' ? '_' + item_size : ''));
	input.setAttribute('name', 'item_id_' + item_id + (item_size != '' ? '_' + item_size : ''));
	input.setAttribute('value', new_item_id);
	cell.appendChild(input);

	input = document.createElement('input');
	input.setAttribute('type', 'hidden');
	input.setAttribute('id', 'item_name_' + new_item_id);
	input.setAttribute('name', 'item_name_' + new_item_id);
	input.setAttribute('value', (item_number != '' ? item_number : (item_name != '' ? item_name : item_description)));
	cell.appendChild(input);

	input = document.createElement('input');
	input.setAttribute('type', 'hidden');
	input.setAttribute('id', 'item_description_' + new_item_id);
	input.setAttribute('name', 'item_description_' + new_item_id);
	input.setAttribute('value', ((item_name != '') ? item_name : item_description) + ((item_size != '') ? ' (' + item_size + ')' : ''));
	cell.appendChild(input);

	input = document.createElement('input');
	input.setAttribute('type', 'hidden');
	input.setAttribute('id', 'item_quantity_' + new_item_id);
	input.setAttribute('name', 'item_quantity_' + new_item_id);
	input.setAttribute('value', item_quantity);
	cell.appendChild(input);

	input = document.createElement('input');
	input.setAttribute('type', 'hidden');
	input.setAttribute('id', 'item_price_' + new_item_id);
	input.setAttribute('name', 'item_price_' + new_item_id);
	input.setAttribute('value', item_price);
	cell.appendChild(input);

	input = document.createElement('input');
	input.setAttribute('type', 'text');
	input.setAttribute('id', 'cart_item_quantity_' + new_item_id);
	input.setAttribute('name', 'cart_item_quantity_' + new_item_id);
	input.setAttribute('value', item_quantity);
	input.setAttribute('size', '1');
	input.setAttribute('onchange', 'if(validate_quantity(this, true)){update_cart(' + item_id + ', ' + new_item_id + ', this.value, true);}');
	cell.appendChild(input);
	row.appendChild(cell);
	
	cell = document.createElement('td');
	cell.setAttribute('align', 'left');
	cell.setAttribute('height', '30');
	cell.setAttribute('id', 'cart_item_price_' + new_item_id);		
	cell.appendChild(document.createTextNode(format_currency(parseFloat(item_price) * parseInt(item_quantity))));
		
	row.appendChild(cell);

	cell = document.createElement('td');
	cell.setAttribute('height', '30');
	cell.setAttribute('align', 'center');

	image = document.createElement('img');
	image.setAttribute('src', 'images/merchandise-delete-icon.jpg');
	image.setAttribute('alt', 'Delete Item');
	
	link_node = document.createElement('a');
	link_node.setAttribute('href', 'javascript:remove_from_cart(' + new_item_id + ');');
	link_node.setAttribute('class', 'remove');
	link_node.appendChild(image);
	cell.appendChild(link_node);
	row.appendChild(cell);
	
	return row;
}

/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 3/9/2009
 * @author Ariel Flesler
 * @version 1.4.1
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function($){var m=$.scrollTo=function(b,h,f){$(window).scrollTo(b,h,f)};m.defaults={axis:'xy',duration:parseFloat($.fn.jquery)>=1.3?0:1};m.window=function(b){return $(window).scrollable()};$.fn.scrollable=function(){return this.map(function(){var b=this,h=!b.nodeName||$.inArray(b.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!h)return b;var f=(b.contentWindow||b).document||b.ownerDocument||b;return $.browser.safari||f.compatMode=='BackCompat'?f.body:f.documentElement})};$.fn.scrollTo=function(l,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};if(l=='max')l=9e9;a=$.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=$(k),d=l,p,g={},q=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px)?$/.test(d)){d=n(d);break}d=$(d,this);case'object':if(d.is||d.style)p=(d=$(d)).offset()}$.each(a.axis.split(''),function(b,h){var f=h=='x'?'Left':'Top',i=f.toLowerCase(),c='scroll'+f,r=k[c],s=h=='x'?'Width':'Height';if(p){g[c]=p[i]+(q?0:r-o.offset()[i]);if(a.margin){g[c]-=parseInt(d.css('margin'+f))||0;g[c]-=parseInt(d.css('border'+f+'Width'))||0}g[c]+=a.offset[i]||0;if(a.over[i])g[c]+=d[s.toLowerCase()]()*a.over[i]}else g[c]=d[i];if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],u(s));if(!b&&a.queue){if(r!=g[c])t(a.onAfterFirst);delete g[c]}});t(a.onAfter);function t(b){o.animate(g,j,a.easing,b&&function(){b.call(this,l,a)})};function u(b){var h='scroll'+b;if(!q)return k[h];var f='client'+b,i=k.ownerDocument.documentElement,c=k.ownerDocument.body;return Math.max(i[h],c[h])-Math.min(i[f],c[f])}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);