var swapInterval;
var active_feature = 0;
var srBlurTimer;

if (typeof window.console == 'undefined'){
    window.console = {
        log:function(){}
    };
}

document.observe("dom:loaded", function() {	
	if ($(document.body).hasClassName("page-index")) {
		/* Frontpage animation */

		swapInterval = setInterval(function() {		
			features = $$('.feature-container .feature')
			next_feature = active_feature + 1;
			if (next_feature >= features.size()) { next_feature = 0; }
			
			features[active_feature].setStyle({'z-index':1500})
			features[next_feature].setStyle({'z-index': 1499, 'opacity':1, 'display':'block'});			
			features[active_feature].fade({duration:2.5});
			
			active_feature = next_feature;
		},5000);
		
		$$('.feature-navigation li').each(function (el) { el.observe('click', function (e) { switchFeature(Event.element(e).getAttribute('data-feature')); })});

		/* Part select dropdown */
		
		new Form.Element.Observer('brand_id_select', 0.1, function(e) {
			new Ajax.Updater('model_id_select', '/parts-supplies/model-options-by-brand/'+$('brand_id_select').getValue(), { method: 'get' });
		});
	}
	
	
	/* Assortiment */
	
	if ($(document.body).hasClassName("assortiment-show")) {
		$$('ul.machine_options input').each(function (el) {
			el.observe('click', function(e) {
				calcMachineTotal();
			})
		})
	}
	/* Live search */
	
	new Form.Element.Observer('search', 0.33, function(e) {
		var s = $('search');
		var r = $('searchresults');
		if (s.getValue().length > 1) {
			if (!r.visible() || r.getStyle('opacity') == 0) { r.appear({duration:0.25}); }
			new Ajax.Updater(r, '/search/live', { parameters: { query: s.getValue() } });
		} else {
			if (r.visible()) { r.fade({duration:0.25}); }
		}
	});
	
	$('search').observe('blur', function() {
		srBlurTimer = setTimeout(function () { $('searchresults').fade({duration: 0.5})}, 500);
	});
	
	$('search').observe('focus', function() {
		clearTimeout(srBlurTimer);
	});
	
  /* Menu buttons klikbaar maken */

  $$("ul#menu li li").each(function(li) {
    li.observe('click', function() { window.location.href = li.down('a').getAttribute('href'); });
    li.setStyle('cursor:pointer;');
  });
});

function switchFeature(next_feature) {
	if (next_feature == active_feature) return;
	
	clearInterval(swapInterval);
	
	features = $$('.feature-container .feature');
	
	features[active_feature].setStyle({'z-index':1500})
	features[next_feature].setStyle({'z-index': 1499, 'opacity':1, 'display':'block'});			
	features[active_feature].fade({duration:0.5});

	active_feature = next_feature;
}

function doSearch(e) {
}

function calcMachineTotal() {
	var total = parseFloat($('machine_id').getAttribute("data-price"));
	$$('ul.machine_options input').each(function(el) { if (el.checked) { total = total + parseFloat(el.getAttribute('data-price')) }});
	$('machine_total').innerHTML = "€ " + total.toFixed(2).replace('.',',');	
}

