/*
	The page that includes this script is responsible for setting these document-level variables
	var uaDataSupplierUrl = "#request.uaPageDelegate.encodeNavUid(request.uaSession.nav_uid#";
	var uaHtmlForNewInputRow = "...content...";
	var uaHtmlForPleaseWait = "...content..."
	var uaHtmlForInvalidProductCode
*/

// These can be changed if someday there are SAP style numbers of lengths other than 7
var uaStyleNumberLengthMin = 7;
var uaStyleNumberLengthMax = 7;
// materials to variants mapping
m2v = {};
// materials to web colors
m2c = {};
// materials to images
m2i = {};
// variants to prices
v2p = {};
m2js = {};
// variants to inventory available now
v2i = {};



// --------- BEGIN SCRIPTING -------

// Execute our initialization code when the page first loads
$(document).ready(function() {
	initView();
})		

// This executes when the page first loads
function initView() {
	$("#quickOrderUI input.size1plus").bind("keyup", productNumberEntryHandler);
	$("#quickOrderUI input.size1plus").bind("change", productNumberEntryHandler);
	$("#quickOrderUI input.size1plus").bind("blur", productNumberBlurHandler);
}

// This executes if there is an Ajax problem
$(this).ajaxError(function(error, request, settings) {
	str = "settings {\n";
	for( var k in settings) {
		try {
			if( typeof(settings[k]) == "string" )
			str += "\t"+k+": "+settings[k]+"\n";
		} catch( e ) { }
	}
	str += "}\nresponse: "+escape(request.responseText);
	//document.write(str);
	alert(uaAjaxErrorMessage);
});

// This executes when a user moves out of a text field
// If the number in the field was not a valid product number, say so
function productNumberBlurHandler() {
	var v = $(this).attr('value');
	if ( v && v.length <  uaStyleNumberLengthMin ) {
		// nmw: Clear any 'Invalid product' messages for this field
		$("+ #too_short_code_error", this).remove();
		
		$(this).after(uaHtmlForInvalidProductCode);
	}
}

// This executes when the user does something in a Style number input field
function productNumberEntryHandler(e) {
	// jld: event.target is not universally available, and jquery sets 'this' properly for us
	var target = this;
	var user_input = $.trim(target.value);
	var row_id = $(target).attr('data');

	// jld: Clear any 'Invalid product' messages for this field
	$("+ #too_short_code_error", this).remove();

	// This guards against needless Ajax calls if the user does something but doesn't change the value
	if (target.previousValue == undefined) {
		target.previousValue = user_input;
	} else if (target.previousValue == user_input) {
		return;
	}
	
	// Respond to the user's input
	if (isApparentlyValidStyleNumberEntry(user_input)) {
		var params = {"ajaxCall":"true"};
		params.row_id = row_id;
		params.sap_product_code = user_input;
		
		// Clear out UI for this product and replace it with a 'please wait' indicator of some kind
		container = $(target).parent().parent();
		$("td.detail", container).empty().append(uaHtmlForPleaseWait);

		// disable the submit button during the ajax processing (since submission in the middle causes an ajax error)
		$("#add_to_cart_btn").attr('disabled','disabled');

		// Do actual AJAX request
		$.post(uaDataSupplierUrl, params, onStyleNumberFetchSuccess, "json");
		
	// The user's entry doesn't appear to be a style number, so just blank out the product UI
	} else {
		target.previousValue = null;
		container = $(target).parent().parent();
		$("td.detail", container).empty();
	}
}

// Executes if we get product info back from the server after an AJAX request
function onStyleNumberFetchSuccess(dataFromServer) {
	var row_id = dataFromServer.ROW_ID;
	var new_html = dataFromServer.HTMLTORETURN;
	populateProductRowContainer(row_id, new_html);
	$("#add_to_cart_btn").removeAttr('disabled');
}

// Utility
function populateProductRowContainer(row_id, htmlCode) {
	var container = getProductRowContainer(row_id);
	$("td.detail", container).empty().append(htmlCode);
	// Executes initialization code that should have been inserted as part of the html code from server
	if (m2js[row_id] != undefined) {
		m2js[row_id]()
	}
}

// Executes when the user chooses a material (aka color)
function materialChanged(target) {
	if( target ) {
		var sap_material_code = target.options[target.selectedIndex].value;
		var row_id = $(target).attr('data');
		var size_options = m2v[sap_material_code];
		$('#variants_'+row_id).html(size_options);
		var size_select = document.getElementById('variants_'+row_id);
		size_select.selectedIndex = 0;
		sizeChanged(size_select);
		$('#image_'+row_id).attr("src", m2i[sap_material_code]);
	} else {
		//alert('materialChanged with no target');
	}
}

// Executes when the user chooses a variant (aka size)
function sizeChanged(target) {
	if( target ) {
		try {
			var row_id = $(target).attr('id').slice(9);
			var val = target.options[target.selectedIndex].value;
			
			var qty_select = document.getElementById('qty_'+row_id);
			var qty_available = v2i[val];
			qty_select.options.length = 0;
			for (var i = 0; i < qty_available; i++) {
				if (i < qty_available && i < numOptionsInQtyDropdown) {
					qty_select.options[i] = new Option(i+1,i+1);
				}
			}
			
			$('#price_'+row_id).html(v2p[val]);
		} catch ( e ) {
		}
	} else {
		alert('sizeChanged with no target');
	}
}

function qtyChanged(target) {
	var row_id = $(target).attr('data');
	var size_select = document.getElementById('variants_'+row_id);
	var sap_variant_sku = size_select.options[size_select.selectedIndex].value;
	var qty_available = v2i[sap_variant_sku];
	var qty_requested = target.value;
}


// Executes when the user wants another data entry row
function addInput() {
	var fake_unique_identifier = new Date() - new Date(1970, 1, 1);
	var htmlForNewRow = uaHtmlForNewInputRow.split('%substituterowidhere%').join(fake_unique_identifier);

	// find the last row
	var last_row = $("#input_row_table tr.last");
	
	// add a new row after it
	last_row.after(htmlForNewRow);
	// then shift the class="last" down to the new row
	var new_row = $("+ tr", last_row)
	new_row.addClass('last');
	last_row.removeClass('last');
	// then update the bindings
	initView();

}

// Basic validation function
function isApparentlyValidStyleNumberEntry(value) {
	var re = /[^0-9A-Za-z]/
	return (value != undefined && value.length >= uaStyleNumberLengthMin && value.length <= uaStyleNumberLengthMax && (value.split(re).length == 1) );
}

// Utility
function getProductRowContainer(row_id) {
	return container = $("#quickOrderUI input[data='"+row_id+"']").parent().parent();
}
