// Funtions

//<![CDATA[ 
		   
// Set location to local or remote server
var siteDomain = 'eastercamp.org.nz';

// Question Slider Function
function questionSlider()
{
	$$('.d_questions h3').each(function(header,i) {
		var state = false; //<- need to set this with a function outsife of this function to close all questions at once
		var answer = header.getNext('div');
		answer.slide('out');
		header.addEvent('click',function(e) {
			state = !state;
			answer.slide(state ? 'in' : 'out');
			if(state) {
				header.addClass('active');
			}
			else {
				header.removeClass('active');
			}
		});
		answer.setStyles({
			overflow: '',
			height: 'auto'
		});
	});
}

// Hover Link Function
function hoverLinks()
{
	//select all a element from your page
  	var list = $$('#container a');
		
	list.each(function(element) {
		// We change the default 'link' property to 'cancel' for the morph effect,
		// this will ensures effects are interrupted when the mouse is leaving
		// and entering, so the morph effect being called begin immediately
		element.set('morph', {link : 'cancel'});
		oldcolor=element.getStyle('color');
	    // on mouse enter on our element we put in oldcolor the current color
	    // and we morph to #aaa the result is a fading effect from the font color to #aaa
	    // (you can use morph with any css property)
		element.addEvent('mouseenter', function(){
			element.morph({
				'color': '#000000'
			});
		});
	  	// on mouse leave on our element we morph back to oldcolor
	  	// the result is a fading effect on font color from #aaa to oldcolor
		element.addEvent('mouseleave', function(){
			element.morph({
				'color': oldcolor
			});
		});
	});
}

// News Scrollbar Function
function makeScrollbar(content,scrollbar,handle,horizontal,ignoreMouse){
	var steps = (horizontal?(content.getScrollSize().x - content.getSize().x):(content.getScrollSize().y - content.getSize().y))
	var slider = new Slider(scrollbar, handle, {	
		steps: steps,
		mode: (horizontal?'horizontal':'vertical'),
		onChange: function(step){
			// Scrolls the content element in x or y direction.
			var x = (horizontal?step:0);
			var y = (horizontal?0:step);
			content.scrollTo(x,y);
		}
	}).set(0);
	if( !(ignoreMouse) ){
		// Scroll the content element when the mousewheel is used within the 
		// content or the scrollbar element.
		$$(content, scrollbar).addEvent('mousewheel', function(e){	
			e = new Event(e).stop();
			var step = slider.step - e.wheel * 30;	
			slider.set(step);					
		});
	}
	// Stops the handle dragging process when the mouse leaves the document body.
	$(document.body).addEvent('mouseleave',function(){slider.drag.stop()});
}

// Slideout function fot contactCheck
function slideOut()
{
	new Fx.Slide('contactNotify').slideOut();
} 
	
// Contact Form Checker Function
function contactCheck()
{
	var reg = new RegExp(/^\w+([\.\-]?\w+)*@\w+([\.\-]?\w+)*(\.\w{2,3})+$/);
	var contactSlider = new Fx.Slide('contactNotify');
	var status = {'true': 'open','false': 'close'};

	document.getElementById('contactNotify').style.display = 'block';
	document.getElementById('contactNotify').innerHTML = 'Message sent successfully';
	
	contactSlider.hide();
	
	//find every <form> on the page
	//$$('form').each(function(form) {
							   
	// ** Modified to target a specific form, rather than all forms on the page **
	$$('#contactForm').each(function(form) {
	//add onSubmit event to each form
		
		//form.addEvent('submit', function(e) {
		$('contactForm').addEvent('submit', function(e) {
			//Prevents the default submit event from loading a new page.
			e.stop();
			
			var errors = 0;
			//validate all required fields
			form.getElements('.validateName').each(function(input) 
			{
				if(input.value === '')
				{ input.addClass('error').morph({ 'background-color': '#664c4c','background-position': '230px 5px' }); errors++; }
				
				else if(input.hasClass('error') && input.value != '') 
				{ input.removeClass('error').morph({ 'background-color': '#666666','background-position': '230px -15px' }); }
			});
			
			form.getElements('.validateEmail').each(function(input) 
			{
				if(input.value === '')
				{ input.addClass('error').morph({ 'background-color': '#664c4c','background-position': '230px 5px' }); errors++; }
				
				else if(reg.test(input.value) === false)
				{ input.addClass('error').morph({ 'background-color': '#664c4c','background-position': '230px 5px' }); errors++; }
				
				else if(input.hasClass('error') && input.value != '') 
				{ input.removeClass('error').morph({ 'background-color': '#666666','background-position': '230px -15px' }); }
			});
			
			form.getElements('.validateMessage').each(function(input) 
			{
				if(input.value === '')
				{ input.addClass('error').morph({ 'background-color': '#664c4c','background-position': '360px 5px' }); errors++; }
				
				else if(input.hasClass('error') && input.value != '') 
				{ input.removeClass('error').morph({ 'background-color': '#666666','background-position': '360px -15px' }); }
			});
	
			if(errors === 0)
			{
				$('contactForm').set('send', {onComplete: function() 
				{
					contactSlider.slideIn();
					
					setTimeout('slideOut()', 10000 );
					$('name').set('value', '');
					$('email').set('value', '');
					$('message').value = '';
				}
			});
				//Send the form.
				$('contactForm').send();
			}
			return errors ? false : true;
		});	
	});
};

// Google Maps function
function googleMap() 
{
	var myLatlng = new google.maps.LatLng(-43.429952,172.704727);
	var mapCenter = new google.maps.LatLng(-43.435034,172.707739);
	var myOptions = {
	  zoom: 15,
	  center: mapCenter,
	   navigationControl: true,
	   navigationControlOptions: {
			style: google.maps.NavigationControlStyle.ZOOM_PAN
	   },
	
	   mapTypeControl: false,
	   scaleControl: false,
	   scrollwheel: false,
	   draggable: true,
	   // may or may not need the # symbol
	   backgroundColor: '333333',
	   
	   mapTypeId: google.maps.MapTypeId.HYBRID 
	};
 
	var map = new google.maps.Map(document.getElementById("googleMap"), myOptions);

	var contentString = '<div id="mapContent">'+
						'<h4>Spencer Beach Holiday Park</h4>'+
						'<img src="images/logoMaps.jpg" height="70" width="80" />'+
						'<p>104 Heyders Road<br />Spencerville<br />Canterbury 8083<br /><br />'+
						'<a target="_blank" href="http://maps.google.co.nz/maps?f=d&source=embed&saddr=&daddr=104+Heyders+Rd,+Canterbury+8083&hl=en&geocode=FcBPaf0d10NLCilTJeFjuo8xbTG7ReCVb7Xz1Q&mra=ls&sll=-43.529634,172.627487&sspn=0.411707,0.617294&ie=UTF8&ll=-43.576909,172.729797&spn=0.174104,0.291824&t=h">Get Directions</a>'+
						'</p></div>';
	
	var infowindow = new google.maps.InfoWindow({
		content: contentString
	});

	var marker = new google.maps.Marker({
		position: myLatlng,
		map: map,
		title: 'Spencer Beach Holiday Park'
	});
	
	google.maps.event.addListener(marker, 'click', function() {
	  infowindow.open(map,marker);
	});
}

// Twitter Function One
function twitterCallback2(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://www.twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
    statusHTML.push('<li><span>'+status+'</span> <a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li>');
  }
  document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
}

// Twitter Function Two
function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}



// preloadChecker function
function preloadCheck()
{
	// If "load" cookie is already set to "loaded" redirect to the main webpage.
	//if(Cookie.read('load') == 'loaded'){window.location = "http://www."+siteDomain};	
	if(Cookie.read('load') != true)
	{
		reqChecks();
	}
	else
	{
		
		
		// Google Maps Instance
    	
	}
}

// postPreloadChecker function
function postPreloadCheck()
{
	// If "load" cookie is already set to "loaded" redirect to the main webpage.
	if(Cookie.read('load') != 'loaded'){window.location = "/preload"};	
}

// Preload requirment checks function
function reqChecks()
{
	// Check which broswer the user has
	if(/MSIE (\d+\.\d+);/.test(navigator.userAgent))
	{ 
		// if the user is running IE6 or below set IE6 variable to true
		var ieVersion = new Number(RegExp.$1) // capture x.x portion and store as a number
		if(ieVersion === 6){var ie6 = true}else{var ie6 = false};
	}
	
	// Set the inital value of the"Success" variable to false
	var success = false;

	// Write the cookie fo the cookie test
	Cookie.write('test');
	// If the test cookie is detected set "cookieTest" to true and kill test cookie, else set "cookieTest" to false
	if(Cookie.read('test')){var cookieTest = true;Cookie.dispose('test');}else{var cookieTest = false};
	
	// If "ie6" returns true display warning message.
	if (ie6 === true)
	{
		var ie6TrueOutput = '<h1 id="preH1">TwoThousandTen Preloader</h1><h2 class="error">Unsupported Browser</h2>'+
		'<p>Internet Explorer 6 is NOT supported, please upgrade to a modern supported browser such as <a href="http://www.microsoft.com/windows/internet-explorer/default.aspx" target="_blank">Microsoft Internet Explorer 8</a> or <a href="http://www.mozilla.com/en-US/firefox/upgrade.html" target="_blank">Mozilla Firefox 3.5</a> and try again.</p>';
		
		document.getElementById('content').innerHTML = ie6TrueOutput;
		var success = false;
	}
	
	// if cookies are disabled display warning message.
	else if (cookieTest === false)
	{
		var cookieFalseOuput = '<h1 id="preH1">TwoThousandTen Preloader</h1><h2 class="error">Cookies Required</h2>'+
							   '<p>Cookies are either disabled or blocked in your browser, they are required for the preloader to function correctly, please enable cookies and refresh this page.</p>';
		
		document.getElementById('content').innerHTML = cookieFalseOuput;
		var success = false;
	}
	
	// If the browser is not IE6 and javascript/cookies are enabled, set "success" to true and return success message.
	else if (screen.width < 1024)
	{
		var cookieTrueOuput = '<h1 id="preH1">TwoThousandTen Preloader</h1><h2 class="alert">Resolution Warning</h2>'+
							  '<p>A resolution of 1024x768 is the minimun resolution to comfortably view this site, your current resolution is '+screen.width+'x'+screen.height+'. Continue at your own displeasure.</p>'+
							  
							  '<p>Since our new website is a little different this year we must run a preloader to load in most of the larger files used on the site, this process may take awhile for slower connections, but worth the wait as once its done pretty much everything is there.</p>'+
							  '<p>Once the preload completes you will be redirected to the new eastercamp site after a 5 second delay.</p>';
		
		document.getElementById('content').innerHTML = cookieTrueOuput;
		var success = true;		
	}
	
	else if (cookieTest === true)
	{
		var cookieTrueOuput = '<h1 id="preH1">TwoThousandTen Preloader</h1><h2 class="success">No Errors Detected</h2>'+
								  '<p>Cookies and Javascript are enabled and your screen resolution is '+screen.width+'x'+screen.height+', so no worries.</p>'+
								  '<p>Since our new website is a little different this year we must run a preloader to load in most of the larger files used on the site, this process may take awhile for slower connections, but worth the wait as once its done pretty much everything is there.</p>'+
								  '<p>Once the preload completes, the site will be revealed to you.</p>'+
								  '<p>If you get bored with waiting, you can <a id="skipLoad" href="#skip">skip</a> the preloader or jump directly to the <a href="https://www.eastercamp.org.nz/southern/register/" target="_blank">Online Registrations</a> page.</p>';
		
		document.getElementById('content').innerHTML = cookieTrueOuput;
		var success = true;	
	}

	// If the "success" variable is true after compatibilty checks have been made, the preloader function is called.
	if(success === true)
	{
		preLoader();
	}

}		

// Preloader Function
function preLoader()
{	
/*	if(preStop)
	{
		return null;
	}*/
	/* progress bar */
	var progressBar = new dwProgressBar({
		container: $('progress-bar'),
		startPercentage: 0,
		speed:50,
		boxID: 'box',
		percentageID: 'perc',
		displayID: 'text',
		displayText: true
	});
	
			
	$$('#skipLoad').addEvent('click', function()
	{
		Cookie.write('load', 'unknown', {path: '/', domain: '.'+siteDomain});
		document.getElementById('text').innerHTML = '<blink>Preload Complete</blink>';
		events();
	});
	
//	var preloadImages;
//	
//	alert(preloadImages);

//	var preloadImages = new Request.HTML(
//	{
//		url: 'images.php',
//		onSuccess: function(html)
//		{
//			alert(html);
//		},
//		onFailure: function()
//		{
//			alert('IT\'S NOT BLOODY WORKING, YOU POMMY WANKER!');
//		}
//	});
//	
//	preloadImages.send();

	//var preloadImages = new Request.HTML().get('gettime.php');
	
	//alert(preloadImages);
	
	var images = preloadImages;
	
	var loader = new Asset.images(images, {
		onProgress: function(counter,index) {
			progressBar.set((counter + 1) * (100 / images.length));
		},
		onComplete: function() {
			images.each(function(im) {
				new Element('img',{ src:im }).inject($('preloadContainer'));
			});
			
			preloadComplete();
		}
	});
}


function createPhpCookie(){
	new Request.HTML().get('../createCookie.php');	
}

// preloadComplete function
function preloadComplete()
{
	//createPhpCookie();
	// set cookie for browser to know content has been preloaded
	Cookie.write('load', 'unknown', {path: '/', domain: '.'+siteDomain});
	document.getElementById('text').innerHTML = '<blink>Preload Complete</blink>';
	setTimeout ('events()', 3000 );
}

function events()
{
	$$('body').removeClass('noBack');
	$$('#preH1').addClass('hidden');
	$$('#preLoader').addClass('hidden');
	$$('#wrapper').removeClass('hidden');
	//<![CDATA[
	// All Mootools & Javascript instances called here in best load order for page.
	window.addEvent('domready', function() {	
										 
		googleMap();
		
		// MenuMatic Instance
		new MenuMatic();
	
		// SmoothScroll Instance
		new SmoothScroll({ duration:300 }, window);
	
		// Slider Instances
		var oneSlider = new viewer($$('#oneSliderBox img)'),{
			mode: 'alpha',
			sizes: {w:200,h:165},
			interval: 7000,
			fxOptions: {duration:1000}
		});
		oneSlider.play(true);
		
		var twoSlider = new viewer($$('#twoSliderBox img)'),{
			mode: 'alpha',
			sizes: {w:200,h:165},
			interval: 7000,
			fxOptions: {duration:700}
		});
		twoSlider.play(true);
		
		var threeSlider = new viewer($$('#threeSliderBox img)'),{
			mode: 'alpha',
			sizes: {w:200,h:165},
			interval: 7000,
			fxOptions: {duration:400}
		});
		threeSlider.play(true);
		
		var homeBoxOne = new viewer($$('#homeBoxOne img)'),{
			mode: 'top',
			sizes: {w:250,h:138},
			interval: 15000,
			fxOptions: {duration:500}
		});
		homeBoxOne.play(true);
		
		var homeBoxTwo = new viewer($$('#homeBoxTwo img)'),{
			mode: 'bottom',
			sizes: {w:245,h:138},
			interval: 15000,
			fxOptions: {duration:500}
		});
		homeBoxTwo.play(true);
		
		var whatSlider = new viewer($$('#whatSlider img)'),{
			mode: 'left',
			sizes: {w:445,h:190},
			fxOptions: {duration:600}
		});
		whatSlider.play(true);
		
		var leaveSlider = new viewer($$('#leaveSlider1 img)'),{
			mode: 'left',
			sizes: {w:445,h:190},
			fxOptions: {duration:600}
		});
		leaveSlider.play(true);
	
		// Link Hover Instance
		hoverLinks();
	
		// News Scroller Instance	
		makeScrollbar( $('newsContainer'), $('newsScrollbar'), $('newsHandle') );
		
		// Questions Slider & close Instance
		questionSlider();
	
		// Google Maps Instance
		contactCheck();
		
		// Starts Fancy Form
		FancyForm.start();
		
		// Gear Check List Instance
		var checked = 0;
		var special = 0;
		var optional = 0;
		
		// Gear Check List Functions called.
		onLoadReset();
		onClickReset();
		listInputEvents();
		listCheck();
	
	});//]]>
}

// Rreload Redirect Function
function reDirect()
{
	window.location = "http://www."+siteDomain;
}

//
//
//
//
//
//
//
//
//
//

// Gear List Check
function listCheck()
{
	if(checked >= 7 && special >= 3)
	{
		document.getElementById('gearResult').innerHTML = "\"Awesome, you're all set for fun times.\"";
		$('gearResult').morph({ 'background-image': 'url(../images/5stars.png)' });
	}
	else if(checked >= 6 && special >= 1)
	{
		document.getElementById('gearResult').innerHTML = "\"Sweet, you'll be in for a good time.\"";
		$('gearResult').morph({ 'background-image': 'url(../images/4stars.png)' });
	}
	else if(checked >= 6)
	{
		document.getElementById('gearResult').innerHTML = "\"Cool, but sure you've got everything?\"";
		$('gearResult').morph({ 'background-image': 'url(../images/3stars.png)' });
	}
	else if(checked >= 4)
	{
		document.getElementById('gearResult').innerHTML = "\"Keep checking 'em off...\"";
		$('gearResult').morph({ 'background-image': 'url(../images/2stars.png)' });
	}
	else if(checked >= 2)
	{
		document.getElementById('gearResult').innerHTML = "\"Well well, a real survivalist eh?\"";
		$('gearResult').morph({ 'background-image': 'url(../images/1stars.png)' });
	}
	else if(checked >= 0)
	{
		document.getElementById('gearResult').innerHTML = "\"You're really packing lite this year.\"";
		$('gearResult').morph({ 'background-image': 'url(../images/0stars.png)' });
	}
	
	var total = checked + special + optional;
	
	if(total <= 9)
	{
		document.getElementById('gearResultDesc').innerHTML = "0"+total+"/11 =";
	}
	else
	{
		document.getElementById('gearResultDesc').innerHTML = total+"/11 =";
	}
}

// Gear Check List Reset functions
function onLoadReset()
{
	resetList();
}

function onClickReset()
{
	$('resetButton').addEvent('click', function()
	{
		resetList();
	});	
}

function resetList()
{
	checked = 0;
	special = 0;
	optional = 0;
	
	$$('.fancyBox').removeClass('checked');
	$$('.fancyBox').addClass('unchecked');

	listCheck();
}

// Gear List Input Events
function listInputEvents()
{
	$$('.box').addEvent('click', function()
	{
		if(this.getProperty('checked') == true)
		{
			this.setProperty('checked', true);
			checked++;
		}
		else
		{
			this.removeProperty('checked');
			checked--;
		}
		listCheck();
	});

	$$('.box2').addEvent('click', function()
	{
		if(this.getProperty('checked') == true)
		{
			this.setProperty('checked', true);
			special++;
		}
		else
		{
			this.removeProperty('checked');
			special--;
		}
		listCheck();
	});
	
		$$('.box3').addEvent('click', function()
	{
		if(this.getProperty('checked') == true)
		{
			this.setProperty('checked', true);
			optional++;
		}
		else
		{
			this.removeProperty('checked');
			optional--;
		}
		listCheck();
	});
}
//]]> 