// analytics declaration
var pageTracker = _gat._getTracker("UA-9653491-1");
pageTracker._trackPageview();

// make sure these images come in as soon as possible
var loadFirst = ['/images/loading.gif','/images/logo.gif'];
new Asset.images(loadFirst);

// domready event
window.addEvent('domready', function(){	
	// second stage pre loading of images
	var imagePreLoad = ['/images/pin_expand.png','/images/pin.png','/images/clouds_near.png','/images/clouds_far.png','/images/modal.gif','/images/plane.png','/images/background.jpg', '/images/legend.png', '/images/modal_about.gif'];
	new Asset.images(imagePreLoad, {
		onComplete: function(){
			$(document.body).removeClass('loading');
		}
	});
	
	// create the basics elements for the content paginator
	var modalPaginator = new Element('div',{
		'id': 'modal-paginator',
		'html': '<div class="paginator"><div class="scroller"><div class="page-container"></div></div></div>'
	});
	
	// dynamically create pages by pulling content from pins
	var paginatorPageContainer = modalPaginator.getElement('.page-container');
	$$('#city-center .pin .modal-content').each(function(item, index){
		var page = new Element('div', {	'class': 'page'	});
		item.getChildren().inject(page);
		page.inject(paginatorPageContainer);		
	});
	
	// creates the styled scroll bars on the content
	// the element needs to be visibile in the dom so that the scroll bars can be created which explains the following mess
	var scrollBars = new Array();
	modalPaginator.setStyles({ 'position': 'fixed', 'top': '-9999px' });
	modalPaginator.inject(document.body);
	modalPaginator.getElements('.scroll-wrapper').each(function(item, index){
		scrollBars[index] = new ScrollBar(item);
	});	
	modalPaginator = modalPaginator.dispose();
	modalPaginator.setStyles({ 'position': 'static' });
	
	// instanciate our classes
	var paginator = new Paginator(modalPaginator.getElement('.paginator'));
	var modalWindow = new Modal({
		onShowComplete: function(){
			// we need to refresh the styled scroll bars because they get out of sync
			scrollBars.each(function(item){
				item.vUpdateThumbContentScroll();
			});
			
			// We need to autopopulate the dropdown on the contact page depending on which modal window user is coming from.
			// Listen for click event on the Contact element, get its id, then map out the id to the appropriate dropdown index. 
			if($('selSegment')) {	
				$('selSegment').selectedIndex = 0; // reset - if user goes straight to the Contact page
			}
			
			$$('.skip-to').addEvent('click', function(e){
				var section = $(e.target).get('id').split('-')[0];
				if($('selSegment')) {	
					switch (section) {
						case 'welcome':
							$('selSegment').selectedIndex = 1;
							break;
						case 'why':
							$('selSegment').selectedIndex = 2;
							break;
						case 'bigexposure':
							$('selSegment').selectedIndex = 3;
							break;
						case 'realresults':
							$('selSegment').selectedIndex = 4;
							break;
						case 'enhancements':
							$('selSegment').selectedIndex = 5;
							break;
						case 'insights':
							$('selSegment').selectedIndex = 6;
							break;
						case 'latino':
							$('selSegment').selectedIndex = 7;
							break;
						case 'nada':
							$('selSegment').selectedIndex = 8;
							break;
						case 'access':
							$('selSegment').selectedIndex = 9;
							break;
					}
				}
			});			
		}
	});
	
	// add event that shows paginator in modal window on pin click	
	var pins = new Pins('.pin');
	$$('.pin').addEvent('click', function(){
		// prepare the paginator so the correct item is selected
		var index = this.get('id').split('-')[1] - 1;
		paginator.toIndex(index, true);
		// show paginator
		modalWindow.show(modalPaginator);
		// track pin clicks in google analytics
		var pinTitle = this.getElement('h2').get('text');
		pageTracker._trackEvent('Pins', pinTitle);
	});
	
	// legend
	var legend = $('legend')
	legend.addEvents({
		'click': function(event){
			var target = $(event.target);
			if(target.get('tag') == 'a'){
				event.preventDefault();
				// get the id from the hash on the anchor
				var index = target.get('href').split('-')[1] -1;
				paginator.toIndex(index, true);
				// show paginator
				modalWindow.show(modalPaginator);
				// hide after click
				this.fireEvent('mouseleave');
			}
		},
		'mouseenter': function(){
			var wrapper = this.getElement('.wrapper');
			wrapper.tween('height', wrapper.getScrollSize().y);
		},
		'mouseleave': function(){
			var wrapper = this.getElement('.wrapper');
			wrapper.tween('height', '0px');
		}
	});
	
	// build tour/about modal window
	var tour = $('tour-the-town');
	var modalIntro = new Element('div', {'id':'modal-about'});
	tour.getElement('.modal-content').inject(modalIntro);
	tour.addEvent('click', function(event){
		event.stop();
		modalWindow.show(modalIntro);
	});
		
	// set up sky animations
	if(!(Browser.Engine.trident && Browser.Engine.version <= 4)){
		$('clouds-far').get('tween', {
			property: 'background-position',
			duration: 900000,
			transition: 'linear',
			fps: 30,
			onComplete: function(){
				this.start('-1920px 0px', '1920px 0px');
			}
		}).start('-1920px 0px', '1920px 0px');
		$('plane').get('tween', {
			property: 'background-position',
			duration: 50000,
			transition: 'linear',
			fps: 30,
			onComplete: function(){
				this.start('1700px 0px', '-1700px 0px');
			}
		}).start('1700px 0px', '-1700px 0px');
		$('clouds-near').get('tween', {
			property: 'background-position',
			duration: 300000,
			transition: 'linear',
			fps: 30,
			onComplete: function(){
				this.start('-1920px 0px', '1920px 0px');
			}
		}).start('-1920px 0px', '1920px 0px');
	}
	
	//set up deep link to specific content
	var content = window.location.hash;
	switch (content) {
		case '#welcome':
			paginator.toIndex(0, true);				
			modalWindow.show(modalPaginator);
			break;
		case '#why':
			paginator.toIndex(1, true);				
			modalWindow.show(modalPaginator);
			break;
		case '#bigexposure':
			paginator.toIndex(2, true);				
			modalWindow.show(modalPaginator);
			break;
		case '#realresults':
			paginator.toIndex(3, true);				
			modalWindow.show(modalPaginator);
			break;
		case '#enhancements':
			paginator.toIndex(4, true);				
			modalWindow.show(modalPaginator);
			break;
		case '#insights':
			paginator.toIndex(5, true);				
			modalWindow.show(modalPaginator);
			break;
		case '#autotraderlatino':
			paginator.toIndex(6, true);				
			modalWindow.show(modalPaginator);
			break;
		case '#nada':
			paginator.toIndex(7, true);				
			modalWindow.show(modalPaginator);
			break;
		case '#access':
			paginator.toIndex(8, true);				
			modalWindow.show(modalPaginator);
			break;
		case '#contact':
			paginator.toIndex(9, true);				
			modalWindow.show(modalPaginator);
			break;
	}	
	
	function validateEmail(email){		
		var result = email.test(/\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b/);
		//console.log('result = '+result);
		return result;
	}
	
	//Ex. (999) 999-9999 or (999)999-9999
	function validatePhone(phone){
		var reg = new RegExp(/^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/);
		//var result = phone.test(/\(?\d{3}\W?\s?\d{3}\W?\d{4}/);
		var result = reg.test(phone);
		return result;
	}	
	
	function checkForm() {	
	
		var error = false;
		
		$('generalError').setStyle('display', 'none');	
		$$('label').removeClass('error');
		
		// must have values on all fields
		$$('.contact-input').each(function(input, index){			
			if (input.get('value') == '') {
				$$('label')[index].addClass('error');
				$('generalError').setStyle('display', 'block');				
				error = true;	
				//console.log('empty = '+error);				
			}			
		});
		
		// validate email and phone
		if (!error) {
			emailError = !validateEmail($('txtEmail').get('value'));
			if (emailError) {
				$('generalError').setStyle('display', 'block');
				$$('label')[3].addClass('error');
			}
			
			phoneError = !validatePhone($('txtPhone').get('value'));	
			if (phoneError) {
				$('generalError').setStyle('display', 'block');
				$$('label')[4].addClass('error');
			}
			
			if (emailError || phoneError) {
				error = true;
			} else {
				error = false;
			}
		}
			
		//console.log('error = '+error);
		return error;
		
	}	
	
	// can't listen to form's submit event because the element isn't visible in the dom, so we use event delegation instead
	var bodyElement = $(document.body);
	bodyElement.addEvent('click', function(e){
		var target = $(e.target);	
		if (target.get('id') == 'media-kit-sign') {
			return true;
		}
		else {
			e.stop();			
			if(target.get('id') == 'submit-btn'){		
				
				//if passes validation
				var pass = !checkForm();
				//console.log('pass = '+pass);
				
				if (pass) {
					var myform = this.getElement('form');
					
					//send the form
					myform.set('send', {
						onComplete: function(response) { 
							$('contact-wrap').set('html', response);
						}
					});
					myform.send();
					//console.log('SENT');
				} else {
					return false;
					//console.log('NOT SENT');
				};	
			}
		}
	});
	
});
