window.addEvent('domready', function() {
	
	var vinDisplay = function(data, vinnumber) {
		data.each(function(a) {
		var el = new Element('div', {'class': 'pos'});
		var label = new Element('span', {'html': a.label+': ', 'class' : 'pos-label'}).inject(el);
		var val = new Element('span', {'html': a.value, 'class' : 'pos-value'}).inject(label, 'after');		
		el.inject($('resultdiv'));
		});
		var p = new Element('p', {'html' : 'Direct link to this result: '});
		var inp = new Element('input', {'type': 'text', 'name' : 'hyperlink', 'value' : 'http://saabvin.com/'+vinnumber, 'onclick': 'zaznacz(this);', 'class' : 'hyperlink'}).inject(p);
		var fb = new Element('a', {'type': 'text', 'name' : 'hyperlink', 'target' : '_blank', 'html' : '<img src="http://saabvin.com/img/facebook.jpg" style="padding-left: 15px;" />', 'href' : 'http://www.facebook.com/share.php?u=http://saabvin.com/'+vinnumber}).inject(p);		
		p.inject($('resultdiv'));
	};
	$('vindecoder2').addEvent('submit', function(e) {
		//Prevents the default submit event from loading a new page.
		e.stop();
		
		var vin_number = $('vin_number').value;		
			
		if(vin_number.length < 17) {
			alert('VIN is incorrect');
			return false;
		}			
					
		if(vin_number.substring(0,3).toUpperCase() != 'YS3') {
			alert('The VIN is incorrect or Your car is not a Saab');
			return false;
		}	
		
		//Empty the log and show the spinning indicator.
		var log = $('resultdiv').empty().addClass('ajax-loading');	
		//Set the options of the form's Request handler. 
		//("this" refers to the $('myForm') element).

		var request = new Request.JSON({
			url: 'index.php?task=ajaxVIN&vin_number='+vin_number,
			onComplete: function(jsonObj) {
				$('resultdiv').removeClass('ajax-loading');
				vinDisplay(jsonObj, vin_number);
			}
		}).send();
	
	});
});
