/*
	TATV
	- "QuickQuote" Applet Animation ( initHomeForm() )
	- Brand -> Model selection

	Author: fde/emakina.
*/

var NUM_TABBED_FORMS = 3;
var SLIDESHOW_TAB_INTERVAL = 1000*3;
var DO_THE_HIGHLIGHT_THINGY = false;

function showTab(tabId)
{
	if (!document.getElementById)
		return;
	var formtabs = $('formtabs');
	var lis = formtabs.getElementsByTagName('li');
	for(var i=0;i<lis.length;i++) {
		lis[i].className = '';
	}

	var ptab = $(tabId);
	ptab.className = 'current';

	/* hide tabs */
	for (i=1;i<=NUM_TABBED_FORMS;i++) {
		var elem = $('homeformtab'+i);
		elem.style.display = 'none';
	}

	/* show current form */
	var pform = $('homeform'+tabId);
	pform.style.display = '';
}

var tabSlideShow = null;
var curSlideTab;
var formFocus = false;

function slideTabs()
{
	if (++curSlideTab > NUM_TABBED_FORMS)
		curSlideTab = 1;
	showTab('tab'+curSlideTab);
}

function startSlideTabs() {
	tabSlideShow = window.setInterval(slideTabs, SLIDESHOW_TAB_INTERVAL);
	if (DO_THE_HIGHLIGHT_THINGY) {
		var homeform = $('homeform');
		homeform.style.backgroundColor = '#ffd911';
	}
}
function stopSlideTabs() {
	// interrupt the tabbed 'slideshow'
	if (tabSlideShow != null) {
		clearInterval(tabSlideShow);
		if (DO_THE_HIGHLIGHT_THINGY) {
			var homeform = $('homeform');
			homeform.style.backgroundColor = '#ffe870';
		}
	}
}
	
function focusSlideTabs()
{// form element gained explicit focus, homeform slideshow will not restart on mouseout
	formFocus = true;
	stopSlideTabs();
}

function mouseoverSlideTabs()
{// temporarily stops the slideshow
	stopSlideTabs();
}

function mouseoutSlideTabs()
{// if the form didn't gain focus yet (clicking or tab focus to element), continue the slideshow
	if (!formFocus) {
		startSlideTabs(); // restart slide
	}
}

// setup the QuickQuote form 'slideshow'
function initHomeForm()
{
	var i, felems;

	if (!document.getElementById) return;

	var homeform = $('homeform');

	function attachStopSlideTabsEvents()
	{
	// felems must be a collection of elements from the DOM tree	
		var j;
		for (j=0;j<felems.length;j++)
		{
			if (felems[j].nodeName.toUpperCase() == 'INPUT')
			{
				var inputtype = felems[j].getAttribute('type');
				// do not override Siebel's onclick events for the submit buttons
				// WBE 16 04 2008 added for cyclo project
				if (inputtype == 'hidden' || inputtype == 'submit' || inputtype == 'button' || inputtype == 'radio')
					continue;
			}
			
			felems[j].onclick = focusSlideTabs;
			felems[j].onfocus = focusSlideTabs;		
		}
	}
	
	// hide tabbed content except the first
	var homeforms = homeform.getElementsByTagName('div');
	for (i=0;i<homeforms.length;i++) {
		if (homeforms[i].className != 'homeformtab')
			continue;
		if (homeforms[i].id != 'homeformtab1')
			homeforms[i].style.display = 'none';
		
		// attach events to tabs
		felems = $('formtabs').getElementsByTagName('a');
		attachStopSlideTabsEvents(felems);

		// attach events to input fields
		felems = homeform.getElementsByTagName('input');
		attachStopSlideTabsEvents(felems);
		felems = homeform.getElementsByTagName('select');
		attachStopSlideTabsEvents(felems);
	}

	homeform.onmouseover = mouseoverSlideTabs;
	homeform.onmouseout = mouseoutSlideTabs;
	
	// start 'slideshow' of form tabs
	curSlideTab = 1;
	startSlideTabs();
}


/* Brand -> Model selection object */

var TATV_SCRIPTS_ELEM_ID = 'tatv_models_script';
var TATV_MODELS_SCRIPTS_PATH = 'http://www.touring-assurances.be/tatv_scripts/models/';	// where the models Javascript files are stored, relative path!
var formBrandModelObject;

function BrandModelSelection(container_id, savemodel_id, scriptsfolder)
{
	this.brands = new Array();
	this.tatvRestoreModel = '';
	this.selBrand = null;
	this.curBrand = '';
	this.selModel = null;
	this.ctlSaveModel = null;
	this.models_scripts_path = TATV_MODELS_SCRIPTS_PATH + scriptsfolder + '/';

	var containerelem = $(container_id);
	this.selBrand = containerelem.getElementsByTagName('input')[0];
	this.selModel = containerelem.getElementsByTagName('select')[0];

	fruit = container_id;

	// save model state in hidden input field, if provided
	if (savemodel_id) {
		formBrandModelObject = this;
		this.ctlSaveModel = $(savemodel_id).getElementsByTagName('input')[0];

		this.selModel.onchange = function() { 
			console.log('model pick '+this.selectedIndex+' = ['+this.options[this.selectedIndex].value+']');
			formBrandModelObject.ctlSaveModel.value = this.options[this.selectedIndex].value;
		}
		// if saved model, the page reloaded, repopulate models
		if (this.ctlSaveModel.value.length > 0) {
			addEvent(window, 'load', function() { formBrandModelObject.restoreVehicleModels(); } );
		}
	}
	else
	{
		// the model is lost when browser back button is used to go back to the homepage quickapplet, so
		// clear the fields
		if ($('homeform')) {
			addEvent(window, 'load', function(){
				var div = $('homeformtab1');//auto
				if (div.getElementsByTagName('input')[0].type != 'radio'){
					// WBE 15 04 2008 added radiotype exception to resolve issue with radio inputs
					div.getElementsByTagName('input')[0].value = '';
					div.getElementsByTagName('input')[1].value = '';
				}


				var div = $('homeformtab2');//moto

				if (div.getElementsByTagName('input')[0].type != 'radio'){
					// WBE 16 04 2008 added radiotype exception to resolve issue with radio inputs
					div.getElementsByTagName('input')[0].value = '';
					div.getElementsByTagName('input')[1].value = '';
				}
				/*
				var flds = div.getElementsByTagName('input');
				flds.concat(div.getElementsByTagName('select'));
				for (var i=0; i<flds.length; i++) {
					if (flds[i].type=="text" || flds[i].type=='select') {
						flds[i].value = 'p'+Math.random();
					}
				}*/
			});
		}	

	}

}

// returns a string with only alphanumerics that can be used as a filename
BrandModelSelection.prototype.plainFileName = function (str)	{
	return str.toLowerCase().replace(/[^a-zA-Z0-9]/g, '_');
}
	
// onblur event for the brand input
BrandModelSelection.prototype.modelsCallback = function() {
	console.log('modelsCallback()...');
	this.chooseBrand();
}

BrandModelSelection.prototype.loadModels = function (brand)
{
	var dochead = document.getElementsByTagName('head')[0];
	var jsfile = this.models_scripts_path+'models-'+this.plainFileName(brand)+'.js';
console.log('loadModels('+brand+') (file: '+jsfile+')');

	var oldscript = $(TATV_SCRIPTS_ELEM_ID);
	if (oldscript!=null)
		dochead.removeChild(oldscript);

	// if the js file didn't load, the models box should be empty
	this.clearModels();

	var script = document.createElement('script');
	script.src = jsfile;
	script.type = 'text/javascript';
	script.language = 'javascript';
	script.id = TATV_SCRIPTS_ELEM_ID;
	dochead.appendChild(script);
}

BrandModelSelection.prototype.clearModels = function ()
{
	this.selModel.options.length = 0;
	this.setStateModel('');
	this.curBrand = '';
}

BrandModelSelection.prototype.fillModels = function (brand)
{
	console.log('fillModels('+brand+')');
	var items = this.brands[brand];
	this.clearModels();
	for (var i=0; i<items.length; i++) {
		this.selModel[this.selModel.options.length] = new Option(items[i], items[i]);
	}

	this.curBrand = brand;

	if (this.tatvRestoreModel) {
		// restore the last picked model on page reload
		this.setStateModel(this.tatvRestoreModel);
		this.selModel.value = this.tatvRestoreModel;
	} else {
		// OR focus the model combobox after user selected a brand
		if (items.length>0) 
			this.setStateModel(items[0]);
		this.selModel.focus();
	}
}

BrandModelSelection.prototype.chooseBrand = function ()
{

	this.tatvRestoreModel = ''; // user interaction

	// brand in generated scripts is UPPERCASE!
	var sBrand = this.selBrand.value.toUpperCase();

	console.log('chooseBrand('+sBrand+')');

	if (!sBrand.length) {
		this.clearModels();
	}
	else if (!this.brands[sBrand] || !this.brands[sBrand].length)
	{
		this.loadModels(sBrand);
	}
	else if (sBrand!=this.curBrand && this.brands[sBrand])
	{
		this.fillModels(sBrand);
	}
}

// repopulate model selection and set current model
BrandModelSelection.prototype.restoreVehicleModels = function ()
{
	// no user interaction here, restore the last picked model
	this.tatvRestoreModel = this.ctlSaveModel.value;
	
	var sBrand = this.selBrand.value.toLowerCase();
	this.loadModels(sBrand);
}


// set model selection status in hidden control for Siebel
BrandModelSelection.prototype.setStateModel = function (model)
{
	if (this.ctlSaveModel) {
		this.ctlSaveModel.value = model;
	}
}

/*	vehicle selection auto/moto quote */

var vhpl = {

	getParent: function(el, tag)
	{
		if (el == null) {
			return null;
		}
		else if (el.nodeType == 1 && el.tagName.toLowerCase()==tag)
		{
			return el;
		} else {
			return this.getParent(el.parentNode, tag);
		}
	},

	// setup vehicle picklist onclick event to store status in control for Siebel,
	setupVehiclePickList: function()
	{
		var vehicleinlist = false;
		var ctlSaveVehicle = $('ctlSaveVehicle').getElementsByTagName('input')[0];
	
	//	console.log('vhp steup '+ctlSaveVehicle.value);
		var vhpl = $('vehiclepicklist');
		var vhpelems = vhpl.getElementsByTagName('input');
	
		var firstvhp = null;
		var totalvhp = 0;
	
		for (var i=0; i<vhpelems.length; i++) {
			var vhpe = vhpelems[i];
			// there may be other input elements!
			if (vhpe.name == "vhp") {
				if (!firstvhp) {
					firstvhp = vhpe;
				}
				
				totalvhp++;
							
				if (ctlSaveVehicle.value && vhpe.value == ctlSaveVehicle.value) {
					vhpe.checked = true;
					vehicleinlist = true;
					console.log('restored '+vhpe);
					this.vehiclePickListConfirm(vhpe);
				} else {
					vhpe.checked = false;
				}
				vhpe.onclick = this.vehiclePickListOnClick;
			}
		}
	
		// auto pick the only available choice
		if (totalvhp==1) {
			firstvhp.checked = true;
			ctlSaveVehicle.value = firstvhp.value;
			vehicleinlist = true;
		}
	
		if (!vehicleinlist) {
			tatvSetButtonState('btnVehicleProceed', false);
		}
	
	},
	
	getColumnHeaders: function(oElem) {
		var sColLabels = [];
		var oTABLE = vhpl.getParent(oElem, 'table');
		var aTH = oTABLE.getElementsByTagName('th');
		for (var i=0; i<aTH.length; i++) {
			// child tables generated by Siebel with the label and arrows for sorting..
			var aTD = aTH[i].getElementsByTagName('td');
			// we'll assume the first TD contains the column text label
			sColLabels.push(aTD[0] ? aTD[0].innerHTML : '');
		}
		return sColLabels; //['','','CC','PK','KW','p/l'];
	},
	
	vehiclePickListConfirm: function(oElem) {
		// copy vehicle info for user confirmation at bottom of page
		var oTR = vhpl.getParent(oElem, 'tr');
		var aTD = oTR.getElementsByTagName('td');
		var oSPAN;

		var colHeaders = this.getColumnHeaders(oElem);
		colHeaders[1] = '';// don't append 'type' label to the vehicle type
		
		// get vehicle data from columns
		var colData = [];
		colData[0] = '';//skip type
		for (var i=1; i<aTD.length; i++) {
			oSPAN = aTD[i].getElementsByTagName('span')[0];
			s = oSPAN ? oSPAN.innerHTML : aTD[i].innerHTML;
			colData.push(s);
		}
		
		// build selected vehicle descr. string
		s = '';
		for (var i=1; i<aTD.length; i++) {
			if (i<6) {
				s = s + colData[i]+'&nbsp;<span class="suffix">'+colHeaders[i]+'</span>&nbsp;&nbsp;';
			} else {
				s = s + /*'<span class="suffix">'+colHeaders[i]+'</span>&nbsp;'+*/colData[i];/*+'&nbsp;&nbsp;';*/
			}
		}

		//$('vehiclepicklist-choice').style.visibility = 'shown';
		var vhpc = $('vehiclepicklist-choice-s');
		vhpc.innerHTML = s;
	},

	vehiclePickListOnClick: function() {
		vhpl.vehiclePickListConfirm(this);
		$('ctlSaveVehicle').getElementsByTagName('input')[0].value = this.value; 		
		tatvSetButtonState('btnVehicleProceed', true);
		$('btnVehicleProceed').getElementsByTagName('button')[0].focus();
	}
}
