// JavaScript Document

/********************************************************
 PRODUCT CUSTOM FUNCTIONS
 * Override the form submission for AJAX submission, 
   only used when JS is enabled on the browser
*********************************************************/
function init_formsubmission() {

	if (document.getElementById('imgCheckPriceOptions') != null)
	{
		document.getElementById('divProductSelectionContainer').style.display = 'none';
		if (document.getElementById('initialPriceOptionButton') != null)
			document.getElementById('imgCheckPriceOptions').src = document.getElementById('initialPriceOptionButton').value;
	}

	if (document.getElementById('cmdChoose') != null)
		document.getElementById('cmdChoose').style.display = 'none';
}

function submitToWishlistCheck() {

	var bReturn = false;
	var ModelInfo = $('ModelInfo').value.evalJSON(true);
	var request = '/actions/wishlist_checkprodtype.asp?V_ID=' + ModelInfo.model;

	var ajax = new Ajax.Request(request, {

		method: 'get',
		requestHeaders: {Accept: 'application/json'},
		asynchronous: false,
		onSuccess: function(transport) {

			var response = transport.responseText.evalJSON(true);
			if (response.product_type == '1' && response.fabric_count > 0 && ModelInfo.fabric == 'null')
			{
				$('spaInformation').update('You must select a fabric, before adding to your wishlist');
				bReturn = false;
			}
			else
				bReturn = true;

		},

		onException: function(req,exception) {
			alert("The request had a fatal exception thrown.\n\n" + exception);
			return false;
		},
	  	onFailure: function(transport){ alert('There was an error returning the data : submitToWishlistCheck'); }

	});

	return bReturn;

}

function populateVersionOptionGroups(type, value) {

	var url = '';
	var qs = '';
	var qsJSON = '';
	var request = '';

	if (type == 'img')
	{
		url = '/actions/populateversionoptiongroups.asp?Model=' + value;
		qs = $('frmChooseVersionAndOption').serialize();
		qsJSON = qs.toQueryParams();
		request = url + '&' + qs
	}
	else
	{
		url = '/actions/populateversionoptiongroups.asp';
		qs = $('frmChooseVersionAndOption').serialize();
		qsJSON = qs.toQueryParams();
		request = url + '?' + qs
	}

	var ajax = new Ajax.Request(request, {

		method: 'get',
		requestHeaders: {Accept: 'application/json'},
		onSuccess: function(transport) {

			var response = transport.responseText.evalJSON(true);

			for (iLoopA = 0; iLoopA < response.result.vog.vog_item.length; iLoopA++)
			{
				VOG_Control = $('VOG_' + response.result.vog.vog_item[iLoopA].vog_id);
				VOG_Control_Value = $('VOG_' + response.result.vog.vog_item[iLoopA].vog_id).options[$('VOG_' + response.result.vog.vog_item[iLoopA].vog_id).selectedIndex].value;

				// Clear the VOG_Control current options
				for(iLoopB = VOG_Control.options.length - 1; iLoopB >= 0 ; iLoopB--)
					VOG_Control.options[iLoopB] = null;

				// Add the applicable options to the VOG_Control
				for(iLoopB = 0; iLoopB < response.result.vog.vog_item[iLoopA].vo.vo_item.length; iLoopB++)
				{
					var optVO_Item = document.createElement("option");

					optVO_Item.value = response.result.vog.vog_item[iLoopA].vo.vo_item[iLoopB].vo_id;
					optVO_Item.text = response.result.vog.vog_item[iLoopA].vo.vo_item[iLoopB].name;
					
					if (response.result.vog.vog_item[iLoopA].vo.vo_item[iLoopB].vo_id == VOG_Control_Value)
						optVO_Item.selected = true;

					VOG_Control.options.add(optVO_Item);
				}

			}

		},

	  	onFailure: function(transport){ alert('There was an error returning the data : populateVersionOptionGroups') }

	});
	
}

function returnVersionOptionGroups(type, value) {

	var response = '';
	var request = '/actions/returnversionoptiongroups.asp?Model=' + value;

	var ajax = new Ajax.Request(request, {

		method: 'get',
		requestHeaders: {Accept: 'application/json'},
		asynchronous: false,
		onSuccess: function(transport) {

			response = transport.responseText.evalJSON(true);

		},

	  	onFailure: function(transport){ alert('There was an error returning the data : returnVersionOptionGroups') }

	});

	// RETURN a collection of Version Option Groups for the selected Model
	return response;
}

function populateVersionFabricGroups(modelID) {

	var request = '/actions/product_fabricgroup.asp?V_ID=' + modelID;

	var ajax = new Ajax.Request(request, {

		method: 'get',
		requestHeaders: {Accept: 'text/html'},
		onSuccess: function(transport) {

			var response = transport.responseText;
			$('divVersionFabric').update(response);

		},

	  	onFailure: function(transport){ alert('There was an error returning the data : populateVersionFabricGroups') }

	});

}

function chooseVersionAndOption(type, value) {

	var url = '';
	var qs = '';
	var request = '';

	// GET all of the form fields for the querystring
	if (type == 'img')
	{
		request = '/actions/chooseversionandoption.asp?Model=' + value + '&' + getChosenFabric();

		// GET the version option groups available for the selected model
		var VersionOptionGroups = returnVersionOptionGroups(type, value);

		if (VersionOptionGroups.result != null)
		{
			for (iLoopA = 0; iLoopA < VersionOptionGroups.result.vog.vog_item.length; iLoopA++)
			{
				request += '&' + $('VOG_' + VersionOptionGroups.result.vog.vog_item[iLoopA].vog_id).serialize();
			}
		}
	}
	else
	{
		url = '/actions/chooseversionandoption.asp';
		qs = $('frmChooseVersionAndOption').serialize();
		request = url + '?' + qs + '&FO_ID=' + getChosenFabric();
	}

	var ajax = new Ajax.Request(request, {

		method: 'get',
		requestHeaders: {Accept: 'application/json'},
		onSuccess: function(transport) {

			var response = transport.responseText.evalJSON(true);
			var V_ID = response.result.v_id;

			var iLoopA = 0;
			var strVOG = '';
			var strVOG_JSON = '';
			var iVOGPrice = 0;

			if (response.result.vog != null)
			{
				for (iLoopA = 0; iLoopA < response.result.vog.vog_item.length; iLoopA++)
				{
					strVOG += response.result.vog.vog_item[iLoopA].name + ', ';
					strVOG_JSON += '{ "vo_id": "' + response.result.vog.vog_item[iLoopA].vo_id + '" }, ';
					iVOGPrice += parseFloat(response.result.vog.vog_item[iLoopA].price);
				}
				strVOG = strVOG.substring(0, strVOG.length - 2);
				strVOG_JSON = strVOG_JSON.substring(0, strVOG_JSON.length - 2);

				// Set the Version and Version Option names
				$('pChosenModel').update(response.result.vl_name + ' - ' + strVOG);
			}
			else
			{
				$('pChosenModel').update(response.result.vl_name);
			}

			// Set the chosen fabric
			if (response.result.fabric != null)
				$('pChosenModelFabric').update(response.result.fabric.fabric_item[0].fog_name.capitalize() + ': ' + response.result.fabric.fabric_item[0].fo_name);
			else
				$('pChosenModelFabric').update('&nbsp;');

			// Calculate the price, including all options and fabric types
			var iPrice = 0;
			iPrice = parseFloat(response.result.v_price) + parseFloat(iVOGPrice);

			if (response.result.fabric != null) iPrice = iPrice + parseFloat(response.result.fabric.fabric_item[0].fog_price);

			$('spaChosenModelPrice').update(iPrice.toFixed(2));

			if (response.result.fabric != null)
				if (strVOG_JSON != '')
					$('ModelInfo').value = '{ "model": "' + response.result.v_id + '", "fabric": "' + response.result.fabric.fabric_item[0].fo_id + '", "vog": { "vog_item": [ ' + strVOG_JSON + ' ] } } ';
				else
					$('ModelInfo').value = '{ "model": "' + response.result.v_id + '", "fabric": "' + response.result.fabric.fabric_item[0].fo_id + '", "vog": { "vog_item": [ { "vo_id": "null" } ] } } ';
			else
				if (strVOG_JSON != '')
					$('ModelInfo').value = '{ "model": "' + response.result.v_id + '", "fabric": "null", "vog": { "vog_item": [ ' + strVOG_JSON + ' ] } } ';
				else
					$('ModelInfo').value = '{ "model": "' + response.result.v_id + '", "fabric": "null", "vog": { "vog_item": [ { "vo_id": "null" } ] } } ';

			$('aVersionModelInfo').href = '/popups/versionmodelmoreinfo.asp?V_ID=' + V_ID;

		},

	  	onFailure: function(transport){ alert('There was an error returning the data : chooseVersionAndOption') }

	});
	
}

function getChosenFabric() {

	var strChosenFabric = '';

	if ($('divVersionFabric').getElementsByClassName('imgSelected')[0] != null)
	{
		var strFabricName = $('divVersionFabric').getElementsByClassName('imgSelected')[0].name;
		var aryFabricName = strFabricName.split('_');

		strChosenFabric = 'FOG_ID=' + aryFabricName[1] + '&FO_ID=' + aryFabricName[2];
	}

	return strChosenFabric;
}

function cmbModel_OnChange() {

	// Repopulate the version option groups for the selected version
	$('pChosenModelFabric').update('&nbsp;');

	if ($('divVersionFabric').getElementsByClassName('imgSelected')[0] != null)
		$('divVersionFabric').getElementsByClassName('imgSelected')[0].removeClassName('imgSelected');
	
	chooseVersionAndOption('dpd', $('Model').getValue());
	populateVersionOptionGroups('dpd', $('Model').getValue());
	populateVersionFabricGroups($('Model').getValue());
}

function cmbVOGSelect_OnChange() { 

	chooseVersionAndOption();

}

function imgVersion_Click(imgSelected) {

	$('pChosenModelFabric').update();

	var imgOriginal = $(imgSelected).src;
	$(imgSelected).src = '/images/endura/fabricoptions/processing.gif';

	if ($('divVersionSelection').getElementsByClassName('imgSelected')[0] != null)
		$('divVersionSelection').getElementsByClassName('imgSelected')[0].removeClassName('imgSelected');

	if ($('divVersionFabric').getElementsByClassName('imgSelected')[0] != null)
		$('divVersionFabric').getElementsByClassName('imgSelected')[0].removeClassName('imgSelected');

	$(imgSelected).className = 'imgSelected';

	chooseVersionAndOption('img', imgSelected.substring(11, imgSelected.length));
	populateVersionOptionGroups('img', imgSelected.substring(11, imgSelected.length));
	populateVersionFabricGroups(imgSelected.substring(11, imgSelected.length));

	$(imgSelected).src = imgOriginal;

}

function aFabric_Click(imgSelected) {

	var imgOriginal = $(imgSelected).src;
	$(imgSelected).src = '/images/kirton/fabricoptions/processing.gif';

	if ($('divVersionFabric').getElementsByClassName('imgSelected')[0] != null)
		$('divVersionFabric').getElementsByClassName('imgSelected')[0].removeClassName('imgSelected');

	$(imgSelected).className = 'imgSelected';

	var imgSelectedVersion = '';
	if ($('divVersionSelection').getElementsByClassName('imgSelected')[0] != null)
		imgSelectedVersion = $('divVersionSelection').getElementsByClassName('imgSelected')[0];

	chooseVersionAndOption('img', $('Model').getValue());

	$(imgSelected).src = imgOriginal;
}

function imgCheckPriceOptions_Click(openImage, closedImage) {

	var divProductSelectionContainer = document.getElementById('divProductSelectionContainer')
	var imgCheckPriceOptions = document.getElementById('imgCheckPriceOptions');

	if (divProductSelectionContainer.style.display == 'none')
	{
		divProductSelectionContainer.style.display = 'block';
		imgCheckPriceOptions.src = closedImage; //'/images/endura/layout/button_checkpriceoptions_close.jpg';
	}
	else
	{
		divProductSelectionContainer.style.display = 'none';
		imgCheckPriceOptions.src = openImage; //'/images/endura/layout/button_checkpriceoptions_open.jpg';
	}

	return true;
}

function selectAccessoryGroup(AP_ID) {

	var popupUrl = '/popups/accessory_select.asp?P_ID=' + AP_ID + '&V_ID=' + $('Model').options[$('Model').selectedIndex].value + '&returnurl=' + $('postbackurl').getValue();

	if(showIbox(popupUrl, '', parseQuery('height=300&width=600&overlaycolor=#000000&showtitle=false'))) {
		showBG();
		window.onscroll = maintPos;
		window.onresize = maintPos;
	}
}

addEvent(window, 'load', init_formsubmission);

