/**
 * Swart Advocatuur 
 * (c) 2006-2008 Omines - www.omines.com
 * 
 * All rights explicitly reserved - unauthorized reproduction strictly prohibited
 */

// Compatibility stuff
Element.implement({
	effect: function(property, options){
		return new Fx.Tween(this, $extend({property: property}, options));
	}
});

// Site class - main active content wrapper
var Site = {
	start: function()
	{
		// Check if we can use console.log, assuming no
		this.console		= false;
		if (window.console && window.console.firebug != '')
			this.console	= true;
		
		if ($('search-form'))	Search.init();
		if ($('callmenow'))		CallMe.init();
		
		$$('a.lightbox').each(function(el, idx) {
			el.addEvent('click', this.ajaxClick.bindWithEvent(this));
			if(idx == 0) Lightbox.initialize();
		}, this);
		
		$$('a[rel=external]').each(function(e){e.target = '_blank';});

		$('contact-callmenow').addEvent('mouseover', function()		{ $('contact-hint').addClass('contact-callmenow'); });
		$('contact-tellafriend').addEvent('mouseover', function()	{ $('contact-hint').addClass('contact-tellafriend'); });
		$('contact-printpage').addEvent('mouseover', function()		{ $('contact-hint').addClass('contact-printpage'); });
		$('contact-mailmenow').addEvent('mouseover', function()		{ $('contact-hint').addClass('contact-mailmenow'); });
		
		$('contact-printpage').addEvent('click', function()	{
			var test = window.open(
				cleanurl+'?print=1',
				'printpreview',
				'location=0,status=0,scrollbars=1,menubar=1,toolbar=1,resizable=1,height=700,width=700'
			);
			if (!test)
			{
				if (!this.console)
					alert(translations['print-preview-could-not-be-opened']);
				else
					this.log(translations['print-preview-could-not-be-opened'], 3);
			}
		}.bind(this));
				
		$('header').addEvent('mouseout', function(e) {
			if ($('contact-hint').hasClass('contact-callmenow'))	$('contact-hint').removeClass('contact-callmenow');
			if ($('contact-hint').hasClass('contact-tellafriend'))	$('contact-hint').removeClass('contact-tellafriend');
			if ($('contact-hint').hasClass('contact-printpage'))	$('contact-hint').removeClass('contact-printpage');
			if ($('contact-hint').hasClass('contact-mailmenow'))	$('contact-hint').removeClass('contact-mailmenow');
		}.bind(this));
	},
	ajaxClick: function(e)
	{
		e.stop();
		var myElement	= e.target;
		if (myElement.tagName.toLowerCase() == 'img')
			if (myElement.parentElement)
				myElement	= myElement.parentElement;
			else
				myElement	= myElement.getParent();
		Lightbox.showPage(myElement.get('href'));
	},
	log: function(message, level)
	{
		if (!this.console)
			return;
		switch (level)
		{
			case 0:	console.log(message);	break;
			case 1:	console.info(message);	break;
			case 2: console.warn(message);	break;
			case 3: console.error(message);	break;
		}
	}
};

function Log(message)	{ Site.log(message, 0); }
function Info(message)	{ Site.log(message, 1); }
function Warn(message)	{ Site.log(message, 2); }
function Error(message)	{ Site.log(message, 3); }

var Search = {
	init: function()
	{
		this.form		= $('search-form');
		this.input		= $('search-input');
		this.submit		= $('search-submit');
		
		this.translated	= translations['search-type-your-question-here'];
		
		if (this.input.get('value') == '' || this.input.get('value') == ' ')
			this.input.set('value', this.translated);
		else
			this.setActive();
		this.submit.setStyle('display','none');
		this.submit.destroy();
		
		this.input.addEvents({
			'focus': function() { this.setActive(); }.bind(this),
			'blur': function() { this.setInactive(); }.bind(this)
		});
	},
	setActive: function()
	{
		if (this.input.get('value') == this.translated)
			this.input.set('value', '');
	},
	setInactive: function()
	{
		if (this.input.get('value') == '')
			this.input.set('value', this.translated);
	}	
}

var CallMe = {
	init: function()
	{
		this.container	= $('callmenow');
		this.form		= $('callmenow-form');
		this.phone		= $('callmenow-input');
		this.submit		= $('callmenow-submit');
		this.active		= false;
		
		$('callmenow-error').set({'text':'', 'style':'display:none'});
		$('callmenow-success').set({'text':'', 'style':'display:none'});
		$('contact-callmenow').addEvent('click', function() {
			if (!this.active)
			{
				this.active	= true;
				$('callmenow').setStyle('display','');
				$('callmenow-input').focus();
			}
			else
			{
				this.active	= false;
				$('callmenow').setStyle('display','none');
			}
		}.bind(this));
		if ($('contact-content-callmenow'))
			$('contact-content-callmenow').addEvent('click', function() { $('contact-callmenow').fireEvent('click', null, 250); });
		
		this.translated	= [ 
			translations['callmenow-phone-number'],
			translations['callmenow-invalid-phone-number'],
			translations['callmenow-your-request-has-been-sent']
		];
		
		this.form.addEvent('submit', function() { this.submitForm(); return false; }.bind(this));

		this.phone.addEvent('focus', function() { this.phoneSetActive(); }.bind(this));
		this.phone.addEvent('blur', function() { this.phoneSetUnused(); }.bind(this));
		this.phoneSetUnused();
	},
	phoneSetUnused: function()
	{
		if (this.phone.get('value') == '')
		{
			this.phone.set({
				'value':	this.translated[0],
				'styles':	{
					'color':		'#666666',
					'font-style':	'italic'
				}
			});
		}
		//else
			//this.phoneCheckValue();
	},
	phoneSetActive: function()
	{
		this.phone.set('style', {'color':'', 'font-style':''});
		if (this.phone.get('value') == this.translated[0])
			this.phone.set('value', '');
	},
	phoneCheckValue: function()
	{
		this.phone.set('value', this.phone.get('value').replace(/\D/g,""));
		if (this.phone.get('value').length < 10)
		{
			$('callmenow-error').set({'text':this.translated[1], 'style':''});
			return false;
		}
		return true;
	},
	submitForm: function()
	{
		$('callmenow-error').set('text', '');
		if (!this.phoneCheckValue())
			return false;
		var postback	= new Request({
			url:		'/callmenow/',
			method:		'post',
			data:		this.form,
			onComplete:	function() {
				$('contact-callmenow').removeEvents('click');
				$('callmenow-success').set({'html':this.translated[2], 'style':''});
				(function() {
					$('callmenow-success').fade(0);
					(function() { $('callmenow').setStyle('display','none'); }).delay(500);
				}).delay(2000);
				this.form.dispose();
			}.bind(this)
		}).send();
		return false;
	}
};

//Lightbox class - allows floating popups with detailed information
var Lightbox = {
	initialize : function() {
		var closer		= this.close.bind(this);
		this.overlay	= new Element('div', {'id' :'lb-overlay'}).injectInside(document.body).addEvent('click', closer);
		this.box		= new Element('div', {'id' :'lb-box'}).injectInside(document.body);
		this.closelink	= new Element('a', {'id' :'lb-closer', 'title':'close'}).injectInside(this.box).addEvent('click', closer);
		this.content	= new Element('div', {'id' :'lb-content'}).injectInside(this.box);
		this.fx = {
			overlay :this.overlay.effect('opacity', {
				duration :250,
				wait :false
			}),
			box :this.box.effect('opacity', {
				duration :250,
				wait :false
			})
		};
		this.overlay.setStyle('visibility', 'hidden');
		this.box.setStyle('visibility', 'hidden');
	},
	position : function() {
		this.overlay.setStyles( {
			top :0,
			left :0,
			width :window.getScrollWidth(),
			height :window.getScrollHeight()
		});
		this.box.setStyles( {
			display :'',
			top :(window.getScrollTop() + 75) + 'px'
		});
	},
	clickLink : function(e) {
		if ($('leftbar-figures'))
			$('leftbar-figures').setStyle('display','none');

		e.stop();
		var myElement	= e.target;
		if (myElement.tagName.toLowerCase() == 'img')
			if (myElement.parentElement)
				myElement	= myElement.parentElement;
			else
				myElement	= myElement.getParent();
		this.showPage(myElement.get('href'));
	},
	showPage : function(getUrl) {
		this.position();
		this.fx.box.start(1);
		$('lb-content').set('html', '<img src="/static/images/ajax-loader.gif" alt="Loading..." />');
		new Request.HTML( {
			url : getUrl,
			method :'get',
			update :$('lb-content'),
			onSuccess : function(responseTree, responseElements, responseHTML, responseJavaScript) {
				$('lb-content').set('html', responseHTML);
				if ($('lb-content').hasChild('currentPage'))
				{
					$('currentPage').set('value', $('pagetitle').get('text'));
					$('currentUrl').set('value', window.location);
				}
			}.bind(this)
		}).send();
		this.fx.overlay.start(0, 0.5);
	},
	close : function() {
		this.fx.overlay.start(0);
		this.fx.box.start(0);
		if ($('leftbar-figures'))
			$('leftbar-figures').setStyle('display','');
	}
};

//Validation functions
function validateMailMeForm()
{
	var errors = new Array();
	var valid = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i
	if(!$('mailmenow-name').value.length)
		errors.push('- '+translations['mailmeform-your-name-is-empty']);
	if(!$('mailmenow-email').value.length && !$('mailmenow-phone').value.length)
		errors.push('- '+translations['mailmeform-email-or-phonenumber-is-required']);
	if($('mailmenow-email').value.length && !valid.test($('mailmenow-email').value))
		errors.push('- '+translations['mailmeform-email-invalid']);
	if(!errors.length)
	{
		$('ajax-submitting').setStyle('display', '');
		new Request.HTML({
			url: '/mailme',
			method: 'post',
			data: $('mailmeform'),
			update: $('lb-content')
		}).send();
	}
	else
		alert(errors.join("\n"));
	return false;
}
function validateTellAFriendForm()
{
	var errors = new Array();
	var valid = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i
	if(!$('tellafriend-your-name').value.length)
		errors.push('- '+translations['tellafriend-your-name-is-empty']);
	if(!$('tellafriend-your-email').value.length)
		errors.push('- '+translations['tellafriend-your-email-is-empty']);
	if(!$('tellafriend-friend-name').value.length)
		errors.push('- '+translations['tellafriend-friend-name-is-empty']);
	if(!$('tellafriend-friend-email').value.length)
		errors.push('- '+translations['tellafriend-friend-email-is-empty']);
	if($('tellafriend-your-email').value.length && !valid.test($('tellafriend-your-email').value))
		errors.push('- '+translations['tellafriend-your-email-invalid']);
	if($('tellafriend-friend-email').value.length && !valid.test($('tellafriend-friend-email').value))
		errors.push('- '+translations['tellafriend-friend-email-invalid']);
	if(!errors.length)
	{
		$('ajax-submitting').setStyle('display', '');
		new Request.HTML({
			url: '/tellafriend',
			method: 'post',
			data: $('tellafriend'),
			update: $('lb-content')
		}).send();
	}
	else
		alert(errors.join("\n"));
	return false;
}

// Set event to start running active content when DOM is loaded
window.addEvent('domready', function() { Site.start(); });
