
document.observe("dom:loaded", initPieSlider);
document.observe("dom:loaded", fixCufonLineHeight);
document.observe("dom:loaded", fixIE6MenuPages);
document.observe("dom:loaded", startHomepageSlideshow);



function initPieSlider()
{
	// set up the slider on the homepage. the ul  keeps track of the current group of pies
	// and the animating logic. listeners on the arrows call that func with a T/F depending
	// on the direction we need to go.
	
	if ($('pieslider') == null)
		return;
	
	var ul = $('pieslider').down('ul');
	
	// set inital offset to the middle group
	var groupsize = $$('#pieslider li a[rel*=pies0]').length;
	//var group = Math.floor(($$('#pieslider li').length / groupsize) / 2) ;
	var group = Math.round(((1 + ((3 - (groupsize%3) ) % 3)) * groupsize) / 3);
	
	ul.setStyle({'marginLeft': (-1 * $$('#pieslider li')[group * 3].offsetLeft) + 'px'});


	
	ul.currentPieGroup = group;
	ul.animating = false;
	
	ul.slideDisplay = function (showNext) {
		
		this.animating = true;
		
		var pies = $$('#pieslider li');
		
		var groupOffset = (showNext) ? 1:-1;
				
		this.currentPieGroup+=groupOffset;
		
		try {
			
			var offset = (-1*(pies[this.currentPieGroup*3].offsetLeft)) + 'px';
			new Effect.Morph(this, {
				style: 'margin-left:'+offset,
				afterFinish: function () { ul.animating = false; }
			});
			
		} catch (err) { this.animating = false; };

	};
	
	$$('#pieslider a.prev, #pieslider a.next').invoke('observe', 'click', function (e) {

		Event.stop(e);

		var obj = Event.element(e), ul = obj.up().down('ul');
		
		if (ul.animating)
			return;
		
		ul.slideDisplay(obj.hasClassName('next'))
		
	});
	
	$$('#pieslider ul img').invoke('observe', 'mouseover', showPieSliderLabel).invoke('observe', 'mouseout', hidePieSliderLabel);
}

function fixCufonLineHeight()
{
	// cufon's adherence to line-height leaves something to be desired
	// so, move the second line (if there is one) up a few pixels
	
	var cufonLines = $$('.cursive').invoke('select', 'cufon');
	if (cufonLines.length == 0)
		return;
	
	cufonLines.each(function (row) {
		
		var tops = row.pluck('offsetTop'), origTop = tops[0];
		for (var x=0, offset=0; x < tops.length; x++)
		{
			if (origTop < tops[x])
				offset = -4;
			
			row[x].style['marginTop'] = offset + 'px';
		}
		
	});
}

function fixIE6MenuPages() {

	// ie6 is having issues with the columns on the menu pages. this fixes it.
	
	if ($('menucolumn2') == null)
		return;

	if ($('column2').down('.health-warning') == null)
		fixIE6MenuPages.delay(.1);

	$('menucolumn2').absolutize().setStyle({'left':'290px', 'top':'330px'});

	var offset = (330+$('menucolumn2').offsetHeight) - $('menucolumn1').offsetHeight;
	if (offset > 0)
		$('column2').down('.health-warning').setStyle({'marginTop':offset+'px'});
}

function startHomepageSlideshow()
{
	var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;

	if ($('homepage_slideshow') == null)
		return;
	
	if (IE6)
		return $$('#homepage_slideshow img ~ img').invoke('remove');

	new FlipStudios.CrossFadingSlideshow('homepage_slideshow');
}

function validateJobAppForm()
{
	// validation regexes for the pie club form. func returns false if
	// any of these fail, true if they all pass. label tag gets an error
	// css class added if that input validation fails.
	
	var validation = {
		'firstname': /.{1,}/,
		'lastname': /.{1,}/,
		'address': /.{1,}/,
		'city': /.{1,}/,
		'state': /.{1,}/,
		'zip': /.{1,}/,
		'phone': /.{1,}/,
		'email': /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
		'position': /.{1,}/,
		'locations': /.{1,}/,
		'desiredhours': /.{1,}/,
		'school': /.{1,}/,
		'schooladdress': /.{1,}/,
		'degree': /.{1,}/,
		'history1_startdate': /.{1,}/,
		'history1_enddate': /.{1,}/,
		'history1_company': /.{1,}/,
		'history1_title': /.{1,}/,
		'history1_responsibilities': /.{1,}/,
		'history2_startdate': /.{1,}/,
		'history2_enddate': /.{1,}/,
		'history2_company': /.{1,}/,
		'history2_title': /.{1,}/,
		'history2_responsibilities': /.{1,}/
	};

	var invalid = false;
	for (field in validation)
	{
		$(field).up('label').removeClassName('error');

		if ($(field).value.match(validation[field]) != null)
			continue;

		invalid = true;
		$(field).up('label').addClassName('error');
	}
	
	if (invalid)
		alert("Please enter in the required fields.");
	
	return !invalid;
}

function validatePieClubForm()
{
	// validation regexes for the pie club form. func returns false if
	// any of these fail, true if they all pass. label tag gets an error
	// css class added if that input validation fails.
	
	var validation = {
		//'full_name': /[A-Za-z]{3,}/,
		'email': /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i /*,
		'bday_month': new RegExp('^[0]?(' + $A($R(1, 12)).join('|') + ')$'),
		'bday_day': new RegExp('^[0]?(' + $A($R(1, 31)).join('|') + ')$'),
		'bday_year': new RegExp('^(' + $A($R(1900, 2050)).join('|') + ')$') */
	};
	
	var invalid = false;
	for (field in validation)
	{
		$(field).up('label').removeClassName('error');

		if ($(field).value.match(validation[field]) != null)
			continue;

		invalid = true;
		$(field).up('label').addClassName('error');
	}
	
	if (invalid)
		alert("Please enter in the required fields.");
	
	return !invalid;
}

function contactUsGetLocations(state)
{
	// sends ajax request on behalf of the contact us form
	// when user selects a state 

	$('location').up('label').hide().select('option').slice(1).invoke('remove');

	if (state.value == "")
		return;
	
	var theForm = $$('#column2 form').pop(), action = theForm.action, d = new Date();
	theForm.action = location.href;
	
	theForm.request({
		
		method:'post',
		parameters: {'ajax':1, 'nocache': d.toJSON()},
		onComplete: function (resp) { theForm.action=action; contactUsGetLocations_ProcessResults(resp); }				  

	});
}

function contactUsGetLocations_ProcessResults(resp)
{
	eval('resp = ' + resp.responseText);
	
	var location = $('location');
	location.selectedIndex = 0;
	location.up('label').show();
	
	for (id in resp)
	{
		//var option = new Element('option', {value:resp[id]['number']});
		var option = new Element('option', {value:id});
		option.text = resp[id]['location'];
		option.update(option.text);
		
		location.insert(option);
	}
}

function contactUsGetLocations_canSubmit()
{
	if ($$('#column2 select').pluck('value').without('').length != 2)
	{
		alert('Please select a state and restaurant location.');
		return false;
	}
	
	return true;
}




//=================== temp solution added =======================================

function contactUsGetLocations2(state)
{
	// sends ajax request on behalf of the contact us form
	// when user selects a state 

	$('location').up('label').hide().select('option').slice(1).invoke('remove');
	
	if (state.value == "")
		return;
	
	var theForm = $$('#column2 form').pop(), action = theForm.action;
	theForm.action = location.href;
	
	theForm.request({
		
		method:'post',
		parameters: {'ajax':1},
		onComplete: function (resp) { theForm.action=action; contactUsGetLocations_ProcessResults2(resp); }
									  
	});
}

function contactUsGetLocations_ProcessResults2(resp)
{
	eval('resp = ' + resp.responseText);
	
	var location = $('location');
	location.selectedIndex = 0;
	location.up('label').show();
	
	for (id in resp)
	{
		var option = new Element('option', {value:resp[id]['number']});
		//var option = new Element('option', {value:id});
		option.text = resp[id]['location'];
		option.update(option.text);
		
		location.insert(option);
	}
}




//============================================================================================















var GoogleMapsVars = {map:null, gdir:null, geocoder: null, addressMarker: null, initialized:false};

function initGoogleMap()
{
	if (!GoogleMapsVars.initialized && GBrowserIsCompatible())
	{
		GoogleMapsVars.map = new GMap2($('map_canvas'));
		GoogleMapsVars.gdir = new GDirections(GoogleMapsVars.map, $("map_directions"));

		GEvent.addListener(GoogleMapsVars.gdir, "load",function () {$("map_directions").update();});
		
		GEvent.addListener(GoogleMapsVars.gdir, "error", GoogleMapHandleErrors);
		//GoogleMapsVars.map.setCenter(new GLatLng(33.8204871,-118.2903732));
	
		GoogleMapsVars.map.addControl(new GSmallMapControl());
		GoogleMapsVars.map.addControl(new GMapTypeControl());
		
		geocoder = new GClientGeocoder();

		geocoder.getLatLng($('start_addr').value, GoogleMapGeocodeResult);
		
		GoogleMapsVars.initialized = true;
	}
}

function GoogleMapGeocodeResult(point)
{
	if (!point)
	{
		alert("Address not found");
	}
	else
	{
		GoogleMapsVars.map.setCenter(point, 13);
	}
}

function setDirections(obj)
{
	$("map_directions").update('<div>Loading...</div>');
	
	GoogleMapsVars.gdir.load(
		
		"from: " + $('start_addr').value + " to: " + $(obj).up('address').next('input').value,
		
		{ "locale": "en_US" }
		
	);
	
	return false;
}

function GoogleMapHandleErrors(){
	   if (GoogleMapsVars.gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + GoogleMapsVars.gdir.getStatus().code);
	   else if (GoogleMapsVars.gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + GoogleMapsVars.gdir.getStatus().code);

	   else if (GoogleMapsVars.gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + GoogleMapsVars.gdir.getStatus().code);

	   else if (GoogleMapsVars.gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + GoogleMapsVars.gdir.getStatus().code);

	   else if (GoogleMapsVars.gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + GoogleMapsVars.gdir.getStatus().code);

	   else alert("An unknown error occurred.");

	}
	
function LocationsSearchEntireState(obj)
{
	$("map_directions").update();
	
	var locationsList = $('locationsResults').down('ul');
	locationsList.childElements().invoke('remove');
	locationsList.appendChild(
		new Element('li').update('Loading...')
	);
	
	
	new Ajax.Updater(locationsList, location.href,{
		postBody: $H({'start_addr': obj.innerHTML, 'radius':'STATE', 'ajax':'1'}).toQueryString()
	});
	
	return false;
}

function getPieCertificatePopup(id, token)
{
	$$('label.error').invoke('removeClassName', 'error');
//	if ($('name').match(/[a-z]{2,}/i) == null)
//		$('name').up('label').addClassName('error');
	if ($('email').match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i) == null)
		$('email').up('label').addClassName('error');
	
	if ($$('label.error').length > 0)
	{
		alert("Please enter in the required fields.");
		return false;
	}
	
	$('certForm').request({
		onCreate: function () {
			$('certForm').update('<br><p>Submitting...</p>');
		},
		onComplete: function () {
			setTimeout("location.href='thank-you.php'", 500);
		}
	});
	
	return true;
}





/* Crossfading Slideshow on homepage */
if (FlipStudios == undefined || FlipStudios == null)
	var FlipStudios = new Object();

FlipStudios.CrossFadingSlideshow = function (container, args) {
	
	var defaultArgs = {duration:1, wait: 3};
	
	if (args != undefined)
		for (prop in args)
			defaultArgs[prop] = args[props];
	
	container = $(container);
	
	container.childElements().invoke('wrap', 'div').slice(1).invoke('hide').invoke('down').invoke('setStyle', {position: 'static', 'left':'0'});
	
	container.showNext = function () {
		
		var fadeoutItem = container.down();
		
		new Effect.Parallel([
			 	new Effect.Fade(fadeoutItem, {sync:true}),
				new Effect.Appear(fadeoutItem.next(), {sync:true})
			], {
			duration: defaultArgs['duration'],
			afterFinish: function () {
				container.insert({bottom: fadeoutItem});
				container.showNext.delay(defaultArgs['wait']);
			}		
		});
				
	};
	
	container.showNext.delay(defaultArgs['wait']);
	
};




function jobSearch()
{
	var theForm = $$('#column2 form').pop();
	
	new Ajax.Updater('job-results', theForm.action, {
		postBody: theForm.serialize(),
		onCreate: function () { $('job-results').update('Loading...'); }
	});
	
	return false;
}

function submitRateYourPie()
{
	if (!$('pie').value.empty())
		return true;
	
	alert('Please select a pie.');
	return false;
}

function showPieSliderLabel(e)
{	
	var	img = Event.element(e),
		label = $('pie_label').show().update(img.alt),
		offsetLeft = Math.floor((img.width - label.offsetWidth +2) / 2)	/* the extra -2 is because of the border-left and border-right*/;

	label.clonePosition(img, {
		setLeft:true,
		setTop:false,
		setWidth:false,
		setHeight:false,
		offsetLeft: offsetLeft
	});	
}
function hidePieSliderLabel()
{
	$('pie_label').update().hide();
}