/* cfe_tvbg_buy.tvbg.js

*/

// global options; 
var chosenOptions = {
	'modelID': '',
	'options': []
}


/* @updateModel
 *
 * called upon onclick of model radio button(s)
 *
 * sets page up to accomodate chosen model
 */
function updateModel( modelID ) {
	//alert('updating model to ' + modelID );
	$('div.modeloptions').css('display', 'none');
	$('div#opts_'+modelID).css('display', 'block');
	
	chosenOptions.modelID = modelID;
}


/* @addItem
 *
 * called upon Add Item button
 *
 * calcs item ID based on values of modelID and options chosen
 */
function addItem( hrefAddItem ) {
	//alert('will add item to the cart: model:' + gItem_model + ', color:' + gItem_color);
	
	var itemID = '';
	var optCode = '', optVal = '', optsKey = '';
	var qty = 0;
	var modelID = '';
	
		// test the validity of qty
		
	qty = document.formItem.itemQty.value;
	
	if ( !qty || qty < 1 ) {
		alert('Please enter a quantity of at least 1.'); 
		itemID = '';
		return;		
	}	

	// modelID
	modelID = chosenOptions.modelID;
	if (!modelID) {
		alert('Please choose a Model.');
		return;
	}


	// calculate model's option spec string, to be used as key to find model itemID
	//
	// for each option in model, fetch values; separate with ";" (semicolon)

	var first = true;
	for (var i=0; i<models[modelID]['options'].length; i++) { 
		// check option vals
		optCode = models[modelID]['options'][i]['code'];
		optVal = $('[name=opt_'+modelID+'_'+optCode+']').val();

		if (optVal == '--') {
			alert('Please ' + models[modelID]['options'][i]['txtSelect'] + ' for this Model.');
			return;
		}
		optsKey += optCode + ':' + optVal;
		
		if (!first) { optsKey += ';' } else { first = false; }
	}
		
	itemID = models[modelID]['items'][optsKey];
	
///	alert('modelID is: ' + modelID + ' optsKey is: ' + optsKey + ' itemID is ' + itemID );
	

		// now take this itemID and send it with the AddToCart url on the query string
		// - but only if itemID is valid! (not blank)

	if ( !itemID ) {		
		alert('ItemID is invalid!');
		return;
	}
	
	// "jump" to addItem page
	var url = hrefAddItem + '&item=' + itemID + '&qty=' + qty; 
	
		///alert ( 'location url will be:' + url );
	document.location = url;
}


