/*
* Configurator Javascript 
* By Jesse Donat on November 21st, 2007
*/

window.addEvent('domready', function(){
	
	var scrolled_y = Cookie.get('scrolled_y');
	if ( scrolled_y > 0 ) { window.scrollTo(0,scrolled_y); Cookie.remove('scrolled_y');	}
		
	$('manual_update').remove();
	
	$$('.config_select').addEvent('change', function(e){
		var e = new Event(e); //for cross browser goodness
		var i = 0;
		$$('.config_select').each(function(el){
			if(el.value < 1) i++;
			if(el.value == -1) { 
				$('configr').action = 'product_config_custom.php';
				kick_and_submit( $('configr') );
				return;
			}
		});
		if(i < 1 || (e.target.value < 1 && i < 2)) kick_and_submit( $('configr') );
	});
	
	$('configr').addEvent('submit', function(e){
		$('config_container').addClass('thinking');
		$('config_container').setOpacity(.5);
		Cookie.set('scrolled_y', window.getScrollTop());
	});
	
	//hardcoded logic badness
	
	$$('.config_text').addEvent('change', function(e){
		var e = new Event(e); //for cross browser goodness
		switch(e.target.name) {
			case 'text_option[4]':
				e.target.value = getFirstNumeric(e.target.value); 
				if(e.target.value > 100) {
					$('configr').action = 'product_config_custom.php';
					kick_and_submit( $('configr') );
					return;
				}
		}
	});
	
	$$('.config_select').each(function(el){
    
    switch(el.name) {
    	//turns option 17 (configurator 3) into a bold "FB"
        case 'option[17]':
            el.style.display = 'none';
            el.selectedIndex = 1;
            var a = new Element('strong');
            a.setHTML(el.options[el.selectedIndex].text);
            a.injectAfter(el)
    }

	});
	

	//end hardcoded badness
});

function kick_and_submit( the_form ) { if( the_form.fireEvent('submit') ) { the_form.submit(); } }

function isNumeric(sText) { return sText == ''+(sText * 1); }

function getFirstNumeric(sText) {
	for (i = 0; i < sText.length; i++) {
		var a = sText.substring(i, sText.length).toInt();
		if(isNumeric(a)) return a;
	}
	return 0;
}

