var working = 0, mT;

function messageBox(m,action) {
	if (action =='close') {
		closeBox('messageBox',0.6,1)
	}
	else if (action =='update') {
		$('messageBox').update(m);
	}
	else {
		$$('body')[0].insert('<div id="messageBox" style="display:none;"></div>');
		centreElement ('messageBox',1);
		if (mT) clearTimeout(mT);
		mT=null;
		$('messageBox').update(m);
		$('messageBox').appear({ duration: 0.3, delay:0.2 });
		var s = m.split(' ');
		var secondsOut = Math.ceil(s.length/3);
		mT = setTimeout(function () { 
			messageBox(null,'close')
		}
		,(secondsOut*1000));
	}
}

function closeBox(id,overlay) {
	$(id).fade({ duration: 0.3 });
}

function centreElement (e, vert) {
	var theScrolls = document.viewport.getScrollOffsets();
	theLeft = Math.floor(((document.viewport.getWidth())-($(e).getWidth()))/2) + theScrolls[0];
	theTop = Math.floor(((document.viewport.getHeight())-($(e).getHeight()))/2) + theScrolls[1];
	if (theTop < 0) theTop = 0;
	if (vert==1)  {
		$(e).setStyle({ top: '0px' });
		$(e).setStyle({ top: theTop+'px' });
	}
	$(e).setStyle({ left: theLeft+'px' });
	
}

function isValidEmail(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1) return false;
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) return false;
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) return false;
	if (str.indexOf(at,(lat+1))!=-1) return false;
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) return false;
	if (str.indexOf(dot,(lat+2))==-1) return false;
	if (str.indexOf(" ")!=-1) return false;
	return true;			
}

function setUpAll () {
	
	var b=$$('ul#thumbPics li a');
	alertBoxNum=null;
	b.each(function(n){
		$(n.id).observe('click', function (e) {
			Event.stop(e);
			if (working != 1) {
				working=1;
				$('mainPic1').fade({ duration: 0.8, from: 1, to: 0.01, afterFinish: function() {
					$('mainPic1').src = $(n.id).href;
					$('mainPic1').fade({ duration: 0.8, from: 0.01, to: 1, delay:0.2, afterFinish: function() { working=0; } });
				} });
			}
		});
	});
	
	if ($('contactUs') != null) {
		
		Event.observe( 'contactUs', 'submit',function (e) {
		
			Event.stop(e);
		
			if ($('name').present() && $('email').present() && $('enquiry').present()) {
				
				if (isValidEmail($F('email'))) {
		
					var allNodes = Form.serialize('contactUs');
					
					var aj = new Ajax.Request(baseURL+'ajaxStuff.php', {method: 'post', parameters: 'contactUs=1&'+allNodes,onComplete: function(response) {
						messageBox(response.responseText);
						$('contactUs').reset();
					}});
				}
				else messageBox('Please enter a valid email address.');
			}
			else messageBox('Please enter at least your name, email &amp; enquiry.');
		
		});
		
	}
	
}


Event.observe( window, 'load',function () { 
	setUpAll()
});

