/**
 * dependcies:
 * mootools v1.11 (http://mootools.net)
 */

// IE doesn't support console.log
if (typeof console == "undefined") {
	var console = {
		log : function(){}
	};
}

// set HomeHero namespace if not defined already
if (typeof PF == "undefined") {
	var PF = {};
}

PF.winLoaded = false;
PF.domReady = false;
PF.section = null;
PF.fadeChain = new Chain();
PF.timer2 = 0;
PF.ticker = null;

/* ------------------------------------------------------------------------------------------------
 * Page initialization
 * ------------------------------------------------------------------------------------------------
 */



window.addEvent('domready',function() {
	PF.domReady = true;
	PF.section = document.body.id;
});

window.addEvent('load',function() {
	PF.winLoaded = true;
	
	if(PF.section == "locateADealer") {
		PF.locateADealer.init();
	}
	if(PF.section == "technical") {
		PF.technical.init();
	}
	if(PF.section == "news") {
		loadNews();
	}
	if(PF.section == "home") {
		initNewsTicker();
		//PF.initTestimonialsSS();
	}
	if (PF.section == "consumerLanding"){
		PF.HomeIntro.init(3);
		PF.HomeIntro.addEvent("onFinishIntro",PF.HomeCarousel.init.bind(PF.HomeCarousel));
	}
	if (PF.section == "fusion"){
		PF.HomeIntro.init(4);
		PF.HomeIntro.addEvent("onFinishIntro",PF.HomeCarousel.init.bind(PF.HomeCarousel));
	}
	if (PF.section == "ascension"){
		PF.HomeIntro.init(6);
		PF.HomeIntro.addEvent("onFinishIntro",PF.HomeCarousel.init.bind(PF.HomeCarousel));
	}
	if (PF.section == "locateDealer") {
		PF.initLocateADealer();	
	}
	
	PF.initEmail();
});

PF.HomeCarousel = {
	activeNum : 0,
	init : function(){
		this.triggers = $$("#mainMenu a");
		this.triggers[0].addClass("hover");
		this.triggers.each(function(lnk,i){
			lnk.addEvent("mouseenter",this.scrollTo.bind(this,i));
		}.bind(this));
		this.scrollEffect = new Fx.Scroll($("sectionCarousel"), {duration:800,wait:false});
		this.scrollEffect.scrollTo(0);
		window.setTimeout("$('intro').remove();",PF.HomeIntro.fadeDuration);
	},
	
	scrollTo : function(i){
		this.triggers[this.activeNum].removeClass("hover");
		this.scrollEffect.scrollTo(816*i);
		this.triggers[i].addClass("hover");
		this.activeNum = i;
	}
}

PF.HomeIntro = {
	delay : 2000,
	fadeDuration : 800,
	notStarted : false,
	init : function(slideNum){
		this.slideNum = slideNum;
		this.activeNum = 0;
		this.slides = $$("#intro li");
		this.animation = this.fadeOutSlide.periodical(this.delay,this);
	},
	
	fadeOutSlide : function(){
		var slide = this.slides[this.activeNum];
		var nextSlide = this.slides[this.activeNum+1] || null;
		if (nextSlide){
			nextSlide.setStyle("display","block");
		}
		var fadeOut = new Fx.Style(slide,"opacity",{duration:this.fadeDuration,onComplete:function(){
			slide.setStyle("display","none");
		}});
		fadeOut.start(0);
		this.activeNum++;
		if (this.activeNum>=this.slideNum){
			$clear(this.animation);
			this.fireEvent("onFinishIntro");
		}
	}
}
$extend(PF.HomeIntro,new Events);

function initNewsTicker() {
	var url = 'includes/outputTickerNews.php';
	$('newsBar').setHTML('Loading News...');
	new Ajax(url, {
	  method: 'get',
	  onComplete: function(response) {
		$('newsBar').setHTML(response);
		PF.ticker = new Ticker('PF.ticker', 'newsBar', 1, 35);
		PF.ticker.start();
	  }
	}).request();
}

/*
**Loads news from database using an AJAX call
**PHP outputs correct css structure (will probably change in future to keep server side away from presentation)
*/
function loadNews() {
	var url = 'includes/outputNews.php';
	var output = $('newsContent');  //put data in news div
	output.setHTML('Loading News Items...');
	
	new Ajax(url, {
	  method: 'get',
	  onComplete: function(response) {
		output.setHTML(response);
		initNewsAccordion();
	  }
	}).request();
}

function initNewsAccordion() {
	var accordion = new Accordion('#newsContent h4', '#newsContent p', {
		opacity: .5,
		onActive: function(toggler, element){
			//toggler.setStyle('color', '#ff3300');
			toggler.effect('opacity').start(1);
		},
	 
		onBackground: function(toggler, element){
			//toggler.setStyle('color', '#222');
			toggler.effect('opacity').start(.5);
		}
	}, $('newsContent'));
	
	var defaultNews;
	if(!getArguments()) {
		defaultNews = 0;
	}
	else {
		defaultNews = getArguments()['n'].toInt();
	}
	
	accordion.display(defaultNews);
}


function getArguments() {
	if(window.location.search.split('?').length < 2) return false;
	
	var args = window.location.search.split('?')[1].split('&');
	var response = Array();
	
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		response[pair[0]] = pair[1];
	}
	return response;
}

PF.technical = {
	init : function() {
		this.fusion = new Accordion('#fusion h4', '#fusion p', {
			opacity: false,
			onActive: function(toggler, element){
				/*
				var fade = new Fx.Style(toggler, 'opacity');
				fade.start(1);
				*/
			},
		 
			onBackground: function(toggler, element){
				/*
				var fade = new Fx.Style(toggler, 'opacity');
				fade.start(.5);
				*/
			}
		}, $('fusion'));
		
		this.ascension = new Accordion('#ascension h4', '#ascension p', {
			opacity: false,
			onActive: function(toggler, element){
				/*
				var fade = new Fx.Style(toggler, 'opacity');
				fade.start(1);
				*/
			},
		 
			onBackground: function(toggler, element){
				/*
				var fade = new Fx.Style(toggler, 'opacity');
				fade.start(.5);
				*/
			}
		}, $('ascension'));
		
		this.legacy = new Accordion('#legacy h4', '#legacy p', {
			opacity: false,
			onActive: function(toggler, element){
				/*
				var fade = new Fx.Style(toggler, 'opacity');
				fade.start(1);
				*/
			},
		 
			onBackground: function(toggler, element){
				/*
				var fade = new Fx.Style(toggler, 'opacity');
				fade.start(.5);
				*/
			}
		}, $('legacy'));
		
		
		var szNormal = 268, szSmall = 208, szFull = 388;
		var dur = 230;
		var frames = 80;
		
		var menuItems = $$("#productLineSelect li");
		var nav = new Fx.Elements(menuItems, {wait: false, duration: dur, fps: frames, transition: Fx.Transitions.Cubic.easeOut});
		menuItems.each(function(menuItem, i) {
			menuItem.addEvent("mouseenter", function(event) {
				var o = {};
				o[i] = {width: [menuItem.getStyle("width").toInt(), szFull]}
				menuItems.each(function(other, j) {
					if(i != j) {
						var w = other.getStyle("width").toInt();
						if(w != szSmall) o[j] = {width: [w, szSmall]};
					}
				});
				nav.start(o);
			});
			menuItem.addEvent("click", function(event) {
				PF.technical.toggle(this.id.slice(0, -6));
			});
		});
		$("productLineSelect").addEvent("mouseleave", function(event) {
			var o = {};
			menuItems.each(function(menuItem, i) {
				o[i] = {width: [menuItem.getStyle("width").toInt(), szNormal]}
			});
			nav.start(o);
		});
		
		$('fusion').setOpacity(1).setStyle('z-index', 2);
		$('ascension').setOpacity(0).setStyle('z-index', 1);
		$('legacy').setOpacity(0).setStyle('z-index', 1);
	},
	
	toggle : function(newAcc) {
		$$('#productLineSelection div').each(function(accordion) {
			var fade = new Fx.Style(accordion, 'opacity');
			if(accordion.id != newAcc) {
				fade.start(0);
				accordion.setStyle('z-index', 1);	
			}
			else {
				fade.start(1);
				accordion.setStyle('z-index', 2);
			}
		});
	}
}

PF.initLocateADealer = function() {
	var ds = $('dealerSelect');
	ds.addEvent('change', function() {
		var url = 'includes/outputDealer.php?s=' + ds.options[ds.selectedIndex].value + '&r=' + $random(0,9999);
		new Ajax(url, {
		  method: 'get',
		  onComplete: function(response) {
			var fadeOut = new Fx.Style('dealerTable', 'opacity', {
				onComplete : function() { 
					$('dealerTable').setHTML(response);
					$('dealerTable').effect('opacity').start(1);
				}
			});
			fadeOut.start(0);
		  }
		}).request();
	});
}

PF.initTestimonialsSS = function() {
	var testimonialsSlideshow = new Slideshow('homeTestimonial', {
		type: 'wipe', 
		duration: [2500, 10000],
		width: 780, 
		height: 429, 
		images: ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg'], 
		hu: 'media/' 
	});	
}

PF.initEmail = function() {
	$$('.buttonGo').addEvent('click', function() {
		PF.addEmail();
	});
}

PF.addEmail = function() {
	var validEmail = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;
	var email = $('email_address');
	var emailAddress = email.value
	if(validEmail.test(emailAddress)) {
		var url = 'includes/insertEmailRemote.php?e=' + emailAddress;
		new Ajax(url, {
		  method: 'get',
		  onComplete: function(response) {
				if(response == "1") {
					alert("Thank you for signing up, you have been registered to receive the Prospot weekly newsletter.");
				}
				else {
					alert("We are sorry, we could not sign you up for the Prospot weekly newsletter at this time.  Please try again later.");
				}
		  }
		}).request();
	}
	else {
		alert("That is not a valid email");
		email.focus();
		email.select();
	}
}