// 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 (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() {
			images[currentIndex].fade('out');
			images[currentIndex = currentIndex < images.length - 1 ? currentIndex+1 : 0].fade('in');
		};
		/* 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('right','722px');	
	var pop = first.dispose();
	pop.inject(bouncescrollers);
	fx1.start('right', '50px');
	/*
	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 (){
	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 shopFunctions = function(){
	if ($('postageSelector')){
		$('postageSelector').addEvent('change', function(){
			$('cartFm').submit();
		});
	}
	if ($('addToCartBlock')){
		el = $('addToCartBlock');
		submitbutton = el.getElement('input[type=submit]');
		// submitbutton.setProperty('disabled', 'disabled');
		choices = el.getElements('select');
		/*
		if (choices.length){
			el.doNotSubmit = true;
		}
		choices.each(function(choice){
			choice.addEvent('change', function(e){
				if (this.value){
					cantMakeActive = false;
					for(a=0; a<choices.length; a++){
						if ((!choices[a].value) || (choices[a].value == 'Please select')){
							cantMakeActive = true;
						}
					}
					if (!cantMakeActive){
						el.doNotSubmit = false;
					}else{
						el.doNotSubmit = true;
					}
					console.log(":"+cantMakeActive);
				}
			});
		});
		*/
		submitbutton.addEvent('click', function(e){
			el.doNotSubmit = false;
			choices.each(function(choice){
				if(choice.value==0)el.doNotSubmit = true;
				//console.log(choice+":"+choice.value);
			});
			if (el.doNotSubmit){
				alert ('Please make a selection from the drop down options.');
				var e = new Event(e).stop();
			}
			//var e = new Event(e).stop();
		});
	}
	$$('input[type=text]').each(function(el){
		el.initVal = el.value;
		el.addEvents({
			'focus': function(e){
				if (el.value == el.initVal){
					el.value = '';
				}
			},
			'blur': function(e){
				if (!el.value){
					el.value = el.initVal;
				}
			}
		});
	});
	if ($('useSameDetails')){
		var fields = $$('#checkoutForm_2 input[type=text]');
		$('useSameDetails').addEvent('click', function(e){
			if (this.checked){
				$('checkoutBlock_2').set('style', 'display: none');
				fields.each(function(el){
					el.value = '';
				});
			}else{
				$('checkoutBlock_2').set('style', 'display: table');
			}
		});
	}
}
var maillist = function(){
}
window.addEvent('domready', function(){
	external();
	flash();
	slideshows();
	shopFunctions();
});
