/**
 * Custom JS Functions
 */

//-- 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_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_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_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_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_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_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;
}

/**
 * Function used to toggle our course date select menu
 * from disabled to enabled upon checking/unchecking the course
 * @param {string} select_ref
 */
function toggle_course_select(select_ref) {
	if (arguments.length > 0) {
		if ($(select_ref + '_course').checked) {
			$(select_ref + '_date').removeAttribute('disabled');
		} else {
			$(select_ref + '_date').disabled = 'disabled';
			$(select_ref + '_date').selectedIndex = 0;
		}
	} else {
		//nothing passed in, we need to iterate through our fields
		//coming from postback
		the_form = $('course_registration');
		
		for (i = 0, field_total = the_form.length; i < field_total; i++) {
			if (the_form[i].type == 'checkbox' && the_form[i].checked) {
				$(the_form[i].id + '_date').removeAttribute('disabled');
			}
		}
	}
}

/**
 * Function used to validate our course registration form
 * @param {string} the_form
 * @return {boolean}
 */
function validate_course_registration(the_form) {
	if (!validate_form(the_form)) {
		return false;
	} else {
		var c_id = '', course_selected = false;
		//let's iterate through our form fields, and validate any checked courses have dates selected for them
		for (i = 0, field_total = the_form.length; i < field_total; i++) {
			if (the_form[i].type == 'checkbox' && the_form[i].checked) {
				c_id = the_form[i].id.replace(/[^0-9]/g, '');
				
				if ($('c' + c_id + '_date').value == 0) {
					alert('A valid date is required in order to register for a course.');
					$('c' + c_id + '_date').focus();
					return false;
				}
				
				course_selected = true;
			}
		}
			
		if (course_selected == false) {
			alert('You must select at least one (1) course in order to submit your registration.');
			return false;
		}
	}

	return true;	
}

/**
 * Function used to access information about the lates load()
 * results for our Google Maps API
 */
function gdirections_load() {
	//Example:
	// document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	// and yada yada yada...
}

/**
 * Function used to handle errors with our 
 * Google Maps Directions API
 */
function handle_gdirections_errors() {
	var error = '';
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect."); //\nError code: " + gdir.getStatus().code);
	} else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) {
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known."); //\n Error code: " + gdir.getStatus().code);
	} else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) {
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input."); //\n Error code: " + gdir.getStatus().code);
	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
		//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	} else if (gdir.getStatus().code == G_GEO_BAD_KEY) {
		alert("The given key is either invalid or does not match the domain for which it was given."); // \n Error code: " + gdir.getStatus().code);
	} else if (gdir.getStatus().code == G_GEO_BAD_REQUEST) {
		alert("A directions request could not be successfully parsed."); //\n Error code: " + gdir.getStatus().code);
	} else {
		alert("An unknown error occurred.");
	}

	//hide our loader if an error occurred
	if (gdir.getStatus().code != '200') {
		//toggle_element('loading');
	}

	marker.show();
}

/**
 * This function displays the directions on the page
 */
function get_directions() {
	var start_address = trim($('start_address').value);

	if (start_address == '') {
		alert('Please enter a starting address');
		$('start_address').focus();
		return;
	}

	//toggle_element('loading');

	//set our our destination address (from our page variables)
	var dest_address = json_decode(destination);
		
	if (start_address != '' && dest_address != '') {
		gdir.load("from: " + start_address + " to: " + unescape(dest_address.address) + ', ' + unescape(dest_address.city) + ', ' + unescape(dest_address.state) + ', ' + dest_address.zip, {"locale": "en"});
		marker.hide();
	} else {
		$('directions').innerHTML = 'Unable to retrieve driving directions.';
	}

	return;
}

/**
 * Function loads our Google maps script dynamically and
 * call our load_lsc_map function
 */
function load_lsc_map_script() {
	var m_script = document.createElement("script");
	m_script.type = "text/javascript";
	m_script.src = "http://maps.google.com/maps?file=api&v=2.x&key=" + gkey + "&async=2&callback=load_lsc_map";
	document.body.appendChild(m_script);
}

/**
 * Function used to load our lsc directions map, google map w/ directions panel
 */
function load_lsc_map() {
	if (GBrowserIsCompatible()) {
		var map = new GMap2($("map")), dest_address = json_decode(destination), dest_point = new GLatLng(dest_address.latitude, dest_address.longitude);
		map.addControl(new GSmallZoomControl3D());
		map.addControl(new GScaleControl());
		map.setCenter(dest_point, (dest_address.tolerance == 100 ? 6 : (dest_address.tolerance == 50 ? 7 : 9)));

		//directions panel
		gdir = new GDirections(map, document.getElementById("directions"));
		GEvent.addListener(gdir, "load", gdirections_load);
		GEvent.addListener(gdir, "error", handle_gdirections_errors);		

		var point = new GLatLng(dest_address.latitude, dest_address.longitude);
		
		var marker_html = '<div>' +
						  '<h4>Lighting Solutions Center</h4>' + 
						  '<p>' + unescape(dest_address.address) + '<br />' + 
						  unescape(dest_address.city) + ', ' + unescape(dest_address.state) + ' ' + dest_address.zip + '<br />' +
						  '<a href="javascript:;" onClick="$(\'start_address\').select();">Get Directions</a>' +
						  '</p></div>';

		//create our marker object, set up the click event, and add to our map
		marker = new GMarker(point);

		GEvent.addListener(marker, "click", function() {
		  $('start_address').select();
		});

		map.addOverlay(marker);
	}
}

/**
 * Function used to clean up special characters in our
 * link tag's title attribute
 * @param {string} ugly_name
 * @return {string} pretty_name
 */
function prettify(ugly_name) {
    var pretty_name = spacer = '', name_parts = ugly_name.split('_');
    for (i = 0, name_parts_count = name_parts.length; i < name_parts_count; i++) {
        pretty_name += spacer + name_parts[i].substring(0,1).toUpperCase() + name_parts[i].substring(1);
        spacer = ' ';
    }
    return pretty_name;
}

/**
 * Function used to get a list of all our stylesheets as 
 * listed in the head tag of our page
 * @return {array} os
 */
function get_all_stylesheets() {
	//if you want ICEbrowser's limited support, do it this way
	if (!window.ScriptEngine && navigator.__ice_version) {
		//IE errors if it sees navigator.__ice_version when a window is closing
		//window.ScriptEngine hides it from that
		return document.styleSheets;
	}
	
	if (document.getElementsByTagName) {
		//DOM browsers - get link and style tags
		var lt = document.getElementsByTagName('link');
		var st = document.getElementsByTagName('style');
	} else if (document.styleSheets && document.all) {
		//not all browsers that supply document.all supply document.all.tags
		//but those that do and can switch stylesheets will also provide
		//document.styleSheets (checking for document.all.tags produces errors [WHY?!])
		var lt = document.all.tags('LINK'), st = document.all.tags('STYLE');
	} else {
		return []; 
	} //lesser browser - return a blank array
	
	//for all link tags ...
	for(var x = 0, os = []; lt[x]; x++) {
		//check for the rel attribute to see if it contains 'style'
		if(lt[x].rel) { 
			var rel = lt[x].rel;
		} else if (lt[x].getAttribute) {
			var rel = lt[x].getAttribute('rel');
		} else {
			var rel = '';
		}
		
		if (typeof(rel) == 'string' && rel.toLowerCase().indexOf('style') + 1 ) {
			//fill os with linked stylesheets
			os[os.length] = lt[x];
		}
	}
	
	//include all style tags too and return the array
	for(var x = 0; st[x]; x++) {
		os[os.length] = st[x]; 
	}

	return os;
}

/**
 * Function used to activate our selected skin/stylesheet
 */
function change_skin(skin) {
	for (var x = 0, ss = get_all_stylesheets(); ss[x]; x++) {
		//for each stylesheet ...
		if (ss[x].title) {
			//disable the stylesheet if it is switchable
			ss[x].disabled = true;
		}

		//check each title ...
		if (ss[x].title == skin) {
			//and re-enable the stylesheet if it has a chosen title
			ss[x].disabled = false;
			
			//let's create our cookie for our selected skin
			create_cookie('theme_preference', skin, 365);
		}
	}

	if (!ss.length) {
		alert('Your browser cannot change stylesheets');
	}
}

/**
 * Function used to write our skin selection form based off
 * the alternate style sheets in our head tags
 */
function write_skin_selection_form() {
    var doc = '<form id="skin_form" name="skin_form"><select name="skin_select" onchange="change_skin(document.skin_form.skin_select[document.skin_form.skin_select.selectedIndex].value)">';
    var styles = get_all_stylesheets();
    for (var i = 0 ; i < styles.length ; i++) {
        if (styles[i].title) {
            doc += '<option value="' + styles[i].title + '"' + (theme_name == styles[i].title ? ' selected' : '') + '>' + prettify(styles[i].title) + '</option>';
        }
    }
    doc += '</select></form>';
    $('skin_selection').innerHTML = doc;
} 

/**
 * Function used to toggle our product browse/attribute search menu
 * @param {string} mode
 * @param {boolean} save Optional
 */
function toggle_menu(mode, save) {
	if (!save) {var save = false;}

	switch (mode) {
		case 'hide':
			if ($('side-pane')) {$('side-pane').style.display = 'none';}
			break;
		case 'show':
			if ($('side-pane')) {$('side-pane').style.display = 'block';}
			break;			
	}

	//update our cookie if applicable
	if (save) {
		save_product_browse_cookie(mode);
	}
}

