// JavaScript Core Document

function external(){
	var l = $$('a');
	var host = top.location.host;
	l.each(function(el){
		if ((el.getProperty('rel')=='external') || (!el.href.test(host)) || (el.href.test('.pdf'))){
			el.setProperty('target', '_blank');
		}
	});
}

function slideshows(){
	/* settings */
	var logged = $$('.editor');
	// if (logged.length > 0) return false;
	var slideshows = $$('.slideshow');
	slideshows.each(function(container){
		var images = container.getElements('img');
		if (images.length > 1){
			if (container.getProperty('rel')){
				var showDuration = container.getProperty('rel') * 1;
			}else{
				var showDuration = 4000;
			}
			var currentIndex = 0;
			var interval;
			/* opacity and fade */
			images.each(function(img,i){ 
				if(i > 0) {
					img.set('opacity', 0);
				}
			});
			/* worker */
			var show = function() {
				var myFx = new Fx.Morph(images[currentIndex], {'duration': 1000});
				// images[currentIndex].fade('out');
				currentIndex = currentIndex < images.length - 1 ? currentIndex+1 : 0;
				var myFx2 = new Fx.Morph(images[currentIndex], {'duration': 1000});
				// images[].fade('in');
				//myFx.set({'z-index': 1});
				//myFx2.set({'z-index': 2});
				myFx.start({'opacity': 0});
				myFx2.start({'opacity': 1});
			};
			/* start once the page is finished loading */
			window.addEvent('load',function(){
				interval = show.periodical(showDuration);
			});
		}
	});
}

function flash(){
	var movies = $$('.flash');
    movies.each(function(el){
		var container = el.id;
		var id = el.id;
		var target = el.get('rel');
		var dims = el.getSize();
		var width = dims.x;
		var height = dims.y;
		var obj = new Swiff(target, {id: id, width: width, height: height, container: container});
	});
}

function _getmap(){
	var map_exists = $('gmap');
	if (map_exists){
		window.addEvent('load',function(){
			load('gmap');
		});	
		window.addEvent('unload',function(){
			GUnload();
		});	
	}
}

function scrollers(){
	if ($('news_scroller')){
		var acclinks = $$('h3.atStart');
		acclinks.each(function(el){
			el.addEvent('mouseenter', function(){
				el.addClass('activeacc');
			});
			el.addEvent('mouseleave', function(){
				el.removeClass('activeacc');
			});
		});
	
		var lastclicked;
		var previousitem;
	
		var accordion = new Accordion('h3.atStart', 'div.atStart', {
			opacity: false,
			alwaysHide: true,
			show: -1,
			duration: 500,
			onActive: function(toggler, element){
				acclinks.removeClass('activeacc');
				toggler.addClass('activeacc2');
				previousitem = lastclicked;
				lastclicked = toggler;
				if(previousitem){
					previousitem.removeClass('activeacc2');
				}
				//scroll.toElement(lastclicked);
			},
			onComplete: function(toggler, element){
				//alert(this);
				//console.log(lastclicked);
				if(lastclicked.hasClass('activeacc2')){
					//scroll.toElement(lastclicked);
					var elpos = lastclicked.getPosition();
					var pos = {x: 0, y: elpos.y-100};
					// alert (element.getParent().id);
					var myFx = new Fx.Scroll(window).toElement(element.getParent().id);
					// scroll.scrollTo(0,elpos.y-50);
				};
				//alert("remove class from"+element);
				//lastclicked = "";
				//scroll.toElement(toggler);
			},
			onBackground: function(toggler, element){
				//toggler.setStyle('background', '#222');
				//toggler.removeClass('activeacc2');
			}
		}, $('acc'));
	}
}

window.addEvent('load', function(){
	
});

function datePickers(){
	var d = new Date();
	da = d.getDate() + 2;
	mo = d.getMonth();
	ye = d.getFullYear();
	
	fullDate = ye + '-' + (mo < 10 ? '0' + mo : mo) + '-' + (da < 10 ? '0' + da : da);
	new DatePicker('.calendarPicker', {format: 'd/M/Y', inputOutputFormat: 'd/M/Y', allowEmpty: true, minDate: {date: fullDate, format: 'y-m-d'}});
}

function quickContactForm(obj){
	if (obj){
		var fields = obj.getElements('.textfield, textarea');
		fields.each(function(el){
			if (el.get('name') != 'do_not_fill'){
				initialVal = el.getParent().getElement('label');
				if (!el.value){
					el.set('value', initialVal.get('html'));
				}
				el.set('rel', initialVal.get('html'));	
				el.addEvent('focus', function(e){
					if (el.value == el.get('rel')){
						el.value = '';
					}else{
						el.select();
					}
				});
				el.addEvent('blur', function(e){
					if (el.value == ''){
						el.value = el.get('rel');
					}
				});
		}
		});
	}
}

function scrollFaqs(){
	if ($('faqs')){
		var li = $$('#faqs li a');
		li.each(function(el){
			el.addEvent('click', function(e){
				wind = window.location.toString();
				var tar = el.href.toString().replace(wind + '#', '');
				var read = $$('.read').removeClass('read');
				$(tar).addClass('read');
				var myFx = new Fx.Scroll(window).toElement(tar);
				var e = new Event(e).stop();
			});
		});
	}
}

function portfolio(){
	if (!$('portfolio')) return false;
	var links = $$('#pagination a');
	links.each(function(el){
		el.addEvent('click', function(e){
			links.each(function(el2){el2.removeClass('active'); });
			el.addClass('active');
			wind = window.location.toString();
			var xpos = (el.href.toString().replace(wind + '#page_', '') - 1) * 530;
			var myEffect = new Fx.Morph('p_inner', {duration: 1000, transition: Fx.Transitions.Sine.easeOut});
			myEffect.start({'left': -xpos});
			var e = new Event(e).stop();
		});
	});
	var items = $$('.page a');
	items.each(function(el){
		el.addEvent('click', function(e){
			if ($('featured_portfolio')){
				$('featured_portfolio').dispose();
			}
			var p = new Element('div', {'id': 'featured_portfolio'}).set('style', 'opacity: 0');
			var myHTMLRequest = new Request.HTML({
				url:'/portfolio_item.php',
				update: p,
				data: "portfolio_url=" + el.get('rel'),
				method: 'get',
				onComplete: function(){
					p.inject('rcol');
					//var myEffect = new Fx.Tween(p, {duration: 1000}).start({'opacity': [0, 1]});
					var myFx = new Fx.Tween(p);
					// myFx.set('background-color', '#f00');
					myFx.start('opacity', '0', '1');
					$('closeBtn').addEvent('click', function(e2){
						$('featured_portfolio').dispose();
						var e = new Event(e2).stop();
					});
				}
				}).send();
			var e = new Event(e).stop();
		});
	});
}

function bouncescroll(){
	var l;
	var bouncescrollers = $('actual_tweets');
	var first = bouncescrollers.getFirst();
	var fx1 = new Fx.Tween(bouncescrollers,{transition: Fx.Transitions.Quad.easeOut, duration: 500});
	bouncescrollers.setStyle('left','309px');
	var pop = first.dispose();
	pop.inject(bouncescrollers);
	fx1.start('left', '0');
	/*
	first = bouncescrollers.getFirst().get('html');
	l = first.length;
	*/
}

function tweet(){
	if ($('actual_tweets')){
		var req = new Request.HTML({url:'/feeds.php',
			onSuccess: function(html) {
				//Clear the text currently inside the results div.
				//Inject the new DOM elements into the results div.
				$('actual_tweets').adopt(html);
				$('actual_tweets').removeClass('loading');
				if (html != 'Oops, the Tweet feeder is empty!'){
					bouncer = bouncescroll.periodical(6000);
					var bouncer;
				}
			}
		}).send();
	}
}
var accordions = function(){
	var accord = $$('.accordion').each(function(el){
		el.togglers = el.getElements('.toggler');
		el.answers = el.getElements('.answer');
		for (a=0; a<el.togglers.length; a++){
			el.togglers[a].addClass('question');
			var inner = new Element('div', {'html': el.answers[a].innerHTML, 'class': 'innerBlock'});
			el.answers[a].innerHTML = '';
			inner.inject(el.answers[a]);
			el.togglers[a].answerHeight = el.answers[a].getSize().y.toInt() + 10;
			el.answers[a].set('style', 'height: 0; overflow: hidden;');
			el.togglers[a].answer = el.answers[a];
		}
		el.togglers.each(function(el2){
			el2.addEvent('click', function(e){
				this.addClass('visited');
				var myFx = new Fx.Morph(this.answer);
				if (this.answer.getSize().y.toInt() > 0){
					myFx.start({'height': 0});
				}else{
					myFx.start({'height': this.answerHeight + 'px;'});
				}
			});
		});
	});
}

var animateHeader = function(){
	if ($('header')){
		var duration = 1000;
		var toAnimate = $$('#header h3 span');
		toAnimate.each(function(el){
			var myFx = new Fx.Morph(el, {'duration': 1500});
			//alert (toAnimate[toAnimate.currentAnimation].nodeName);
			myFx.set({'opacity': 0});
		})
		toAnimate.animation = animateHeaders.periodical(1000, toAnimate);
		toAnimate.currentAnimation = 0;
	}
}
var datePickers = function (){
	if ($$('.datePicker').length < 1) return false;
	var d = new Date();
	da = d.getDate() + 1;
	mo = d.getMonth();
	ye = d.getFullYear();
	
	fullDate = ye + '-' + (mo < 10 ? '0' + mo : mo) + '-' + (da < 10 ? '0' + da : da);
	new DatePicker('.datePicker', {inputOutputFormat: 'Y-m-d', allowEmpty: true, minDate: {date: fullDate, format: 'Y-m-d'}});
}
var animateHeaders = function(){
	toAnimate = this;
	if (toAnimate.currentAnimation < toAnimate.length){
		var myFx = new Fx.Morph(toAnimate[toAnimate.currentAnimation], {'duration': 1500});
		//alert (toAnimate[toAnimate.currentAnimation].nodeName);
		myFx.start({'opacity': 1});
		toAnimate.currentAnimation = toAnimate.currentAnimation + 1;
	}else{
		$clear(toAnimate.animation);
	}
}
function itemFade(el){
	var el = el ? el : this;
	if (el.items.length > 1){
		var fx = new Fx.Tween(el.items[el.currentItem],{transition: Fx.Transitions.Quad.easeOut, duration: 500});
		fx.start('opacity', 0);
		
		var fx1 = new Fx.Tween(el.items[el.nextItem],{transition: Fx.Transitions.Quad.easeOut, duration: 500});
		fx1.set('opacity', 0);
		fx1.start('opacity', 1);
		
		temp = el.nextItem;
		el.nextItem = el.currentItem + 1 > el.items.length ? 0 : el.currentItem + 1;
		el.currentItem = temp;
	}
}
function itemScroll(){
	var el=this;
	items = el.getElements('.tweet');
	if (el.alreadyMoved){
		var disp = items[0].clone();
		el.set('style', 'margin-top: 0');
		items[0].dispose();
		disp.inject(el, 'bottom');
		
	}
	var fx = new Fx.Morph(el,{
		transition: Fx.Transitions.Quad.easeOut,
		duration: 1000,
	});
	fx.start({'margin-top': -160});
	el.alreadyMoved = true;
}
var feeds = function(){
	if ($('feeds')){
		$('feeds').set('style', 'opacity: 0;'); 
		var myHTMLRequest = new Request.HTML({
			url:'/feeds.php',
			update: $('feeds'),
			onComplete: function(){
				var myFx = new Fx.Tween($('feeds'), {'duration': 1500});
				myFx.start('opacity', '0', '1');
				var el = $('feeds');
				el.height = el.getElement('.tweet').getSize().y.toInt();
				// itemFade(el);
				var scrolling = itemScroll.periodical(6000, el);
			}
		}).send();
	}
}
var homePageAds = function(){
	$$('.home_page_ad').each(function(el){
		el.getElement('p').addClass('hide');
		el.set('style', 'cursor: pointer; ');
		el.addEvents({
			'mouseover': function(e){
				el.getElement('p').removeClass('hide');
			},
			'mouseout':  function(e){
				el.getElement('p').addClass('hide');
			}
		});
	});
};
window.addEvent('domready', function(){
	external();
	flash();
	_getmap();
	slideshows();
	scrollers();
	tweet();
	scrollFaqs();
	quickContactForm($('f'));
	portfolio();
	accordions();
	datePickers();
	if ($('caterBookForm')){
		$('caterBookForm').setProperty('target', '_blank');
	}
	feeds();
	animateHeader();
	homePageAds();
});
