//main.js
var emailText = 'Email Address';
var emailErrorMsg = 'Please enter a valid email';
var currentSocialPane = 'twitter';
var socialPaneList = Array('youtube','twitter','facebook');
$(document).ready(function(){
	
	// make enter submit forms through ajax
	$('input[type=text], input[type=email]').keyup(function(event,el){
		
		var thisForm = $(this).attr('data-formId');
		if (event.keyCode == 13) {
			showVerifyAge(thisForm);
		}
	});
	
		// bind inputs for active state
	$('input[type=text],input[type=email]').live('focus',function(){
		$(this).toggleClass('active');
		if($(this).attr('value') == emailText || $(this).attr('value') == emailErrorMsg){
			$(this).attr('value','');
		}
	});
	
	$('input[type=text],input[type=email]').live('blur',function(){
		$(this).toggleClass('active');
		if($(this).attr('value') == '' && $(this).attr('name') == 'email'){
			$(this).attr('value',emailText);
		}
	});
	
	// init lightboxes
	$('.lb').fancybox();
	
	$('input[type=radio]').ezMark();
	
	
	// top menus
	$('.dropDownTrigger.open').live('mouseleave',function(){
		var el = $(this);
		setTimeout(function(){
			
			el.find('.dropDown').slideUp(400,'easeInOutQuint');
			el.removeClass('open');
		},2000); // closes by itself after 2 sec of mouse out
	});

	$('.dropDownTrigger').live('click',function(){
		
		// if this is open, leave it open
		if($(this).hasClass('open')){
			// close this
			$(this).find('.dropDown').slideUp();
			$(this).removeClass('open');
		} else {
			// otherwise close others
			$('.dropDownTrigger.open .dropDown').slideUp(400,'easeInOutQuint');
			$('.dropDownTrigger.open').removeClass('open');
			
			// show this one
			var dropDown = $(this).find('.dropDown');
			dropDown.slideDown(400,'easeInOutQuint');
			$(this).addClass('open');
		}
	});
	
	setInterval(function(){
		switchSocial();
	},6000);
	// end top menus
	
});

function toggleFacebook() {
	$('#facebook').toggleClass('hidden');
}

/* ================ begin submission scripts ============== */

function showVerifyAge(formId){
	var inputField = $('#'+formId).find('input[name=email]');
	var emailAddress = inputField.attr('value');
	var validate = validateEmail(emailAddress);
	if(validate) { // validate email first
		$('#verifyAgeTrigger').click();
		// set form id in popup
		$('#verifyAgeForm').find('input[type=button]').attr('data-formId',formId);
	} else {
		inputField.attr('value',emailErrorMsg);
	}
	
	
}

function verifyAge(formId){
	var ageForm = $('#verifyAgeForm');
	var ageString = '';
	ageString = ageForm.find('#month').attr('value') + '/' + ageForm.find('#day').attr('value') + '/' + ageForm.find('#year').attr('value');
	//alert(ageString);
	var check = new Date();
	check.setFullYear(check.getFullYear() - 13);
	if(ageForm.find('#month').attr('value') == '' || ageForm.find('#day').attr('value') == '' || ageForm.find('#year').attr('value') == ''){
		$('#ageVerifacationMsg').html('Please enter your Birthdate');
	
	}else if(isNaN(ageForm.find('#month').attr('value')) || isNaN(ageForm.find('#day').attr('value')) || isNaN(ageForm.find('#year').attr('value'))){
		$('#ageVerifacationMsg').html('Please enter your Birthdate');
	} else if(new Date(ageString).getTime() - check.getTime() < 0){
		// backfill name and birthday, then submit
		var originalFrm = ageForm.find('input[type=button]').attr('data-formId');
		//alert(originalFrm);
		$('#'+originalFrm+' input[name=name]').attr('value',ageForm.find('input[name=name]').attr('value'));
		$('#'+originalFrm+' input[name=birthday]').attr('value',ageString);
		submitEmail(originalFrm);
		
	} else {
		$('#ageVerifacationMsg').html('You must be over 13.');
		ageForm.find('input').each(function(){
			$(this).attr('disabled', true);
		});
	}
	
}
function submitEmail(formId){
	var emailAddress = $('#'+formId).find('input[name=email]').attr('value');
	var name = $('#'+formId).find('input[name=name]').attr('value');
	var birthdate = $('#'+formId).find('input[name=birthday]').attr('value');
	//birthdate = birthdate + '-' + $('#'+formId+' input[name=day]').attr('value');
	//birthdate = birthdate + '-' + $('#'+formId+' input[name=year]').attr('value');
	var data = 'emailAddress='+escape(emailAddress)+'&name='+escape(name)+'&birthdate='+escape(birthdate);
	$.ajax({
		type: 'GET',
		url: '/api/signUp.php',
		data: data,
		success: function(data) {
			if (data == 1){
				
				$('#emailSuccessTrigger').click();
			} else {
				// error with api
				
			}
		}
	});
}

function testSpeed(){
	var speed;
	var d = new Date();	
	var time1 = Math.round((d.getTime())/10)/100;
	var time2;
	var timeDiff;
	var testImage = '/img/testImg.png';
	var data = 'time='+time1;
	var imgSize = 320.131/1024; // MB conversion
	var timeClass = new Array();
	var maxLoadTime = 3; // maxium number of seconds to load the page
	var pageSize = new Array();
	pageSize.push(2.3); // 2.3 MB for full page
	pageSize.push(1); // 1 MB for half completxity // not a real VAL#
	pageSize.push(0.5); // 0.5 MB for 1/4 complexity // not a real VAL#
	
	$.ajax({
		type: 'GET',
		url: testImage,
		data: data,
		success: function(data) {
			d = new Date();
			time2 = Math.round((d.getTime())/10)/100;		
			timeDiff = time2 - time1;
			speed = imgSize/timeDiff;

			// use connection speed to determin which images to use
			var i = 0;
			while (i <= 2){
				if(pageSize[i]/maxLoadTime <= speed) { // if req speed >= actual speed
					alert('fast enough for '+Math.floor(pageSize[i]*100)/100+'MB in '+maxLoadTime+' sec|| ReqSpeed:'+pageSize[i]/maxLoadTime+' mbps || ActualSpeed:'+speed+' mbps || totalTime:'+timeDiff);
				} else {
					alert('**NOT** fast enough for '+Math.floor(pageSize[i]*100)/100+'MB in '+maxLoadTime+' sec|| ReqSpeed:'+pageSize[i]/maxLoadTime+' mbps || ActualSpeed:'+speed+' mbps || totalTime:'+timeDiff);
				}
				i = i + 1;
			}
		}
	});
	
	return speed;
}

function validateEmail(emailAddress){
	var match = emailAddress.toLowerCase().match(/[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})/);
	return match;
}

/* SOCIAL PANE ===================*/

function switchSocial(divId){
	
	//alert(divId);
	if(divId == undefined){ // time to rotate
		//currentSocialPane
		for (pane in socialPaneList){
			if(currentSocialPane == socialPaneList[pane]){
				var target = parseInt(pane) + 1;
			}
		}
		if(target > 2){
			target = 0;
		}
		
		divId = socialPaneList[target];
	}
	
	$('#social.pane .displayPane > div').each(function(){ // hide all children
		$(this).fadeOut();
	});
	$('#social.pane .displayPane #' + divId + "Pane").fadeIn();
	
	currentSocialPane = divId;
	//alert(currentSocialPane);
}
