var headlinerActive = 0;
var autoRotate = true;
var autoRotateTime = 8000;	// milliseconds
var timeout;
var headliners;
var newsworthy;
var newsworthy_page = 0;
var activeBox = 1;
var availableSearchTags;

$(document).ready(function() {
	try {
		Typekit.load();
	}
	catch(e) {}
	
	$('a.lightbox').lightBox();
	$('.accordion').accordion({active:false, autoHeight:false, collapsible:true});
	
	$('#searchForm').submit(function(e) {
		if ($('#searchBox').val() == 'WHAT ARE YOU LOOKING FOR?' || $('#searchBox').val() == '') {
			e.preventDefault();
			return false;
		}
	});
	
	//	remove non-JS code
	$('#billboard').css('opacity','0');
	$('#staticBillboard').remove();
	$('#clickableWindow').show();
	$('#billboard a,#newsworthy a').removeAttr('href');
	$('#calendar_button_clicker').attr('href','#');
	$('#scroller').css('margin-top','0px');

	if ($('#file_upload').attr('name') == 'file_upload') {
		$('#file_upload').uploadify({
		    'uploader'  : '/uploadify/uploadify.swf',
		    'script'    : '/uploadify/check.cfm',
		    'cancelImg' : '/uploadify/cancel.png',
		    'folder'    : '/events/w2w/_uploads',
		    'auto'      : true
  		});
	}

	if ($('#billboard').html()) {
		$.ajax({
			url:		'/_include/homepage.cfm',
			data:		{ajax:true},
			dataType:	"json",
			error:		function() {
				alert('Problem getting our exhibits information!  We apologize for the inconvenience!');
			},
			success:	function(data) {
				headliners = data.headliners;
				newsworthy = data.newsworthy;
				
				$('#backArrow').click(function() {
					headlinerMove('b');
					autoRotate = false;
				});
				$('#nextArrow').click(function() {
					headlinerMove('n');
					autoRotate = false;
				});
				
				prepareHeadliners();
			}
		});

		//	hide left arrow by default in newsworthy
		$('#_leftArrow img').hide();
	
		$('#_leftArrow, #_rightArrow').click(function() {
			var totalPages = Math.ceil(newsworthy.length / 5);
	
			if ($(this).attr('id') == '_rightArrow' && newsworthy_page < totalPages) {
				//	show next ~5
				newsworthy_page++;
				$('#_leftArrow img').show();
			}
			else if ($(this).attr('id') == '_leftArrow' && newsworthy_page > 0) {
				//	show previous 5
				newsworthy_page--;
				$('#_rightArrow img').show();
			}
			else return;
	
			if (newsworthy.length >= (newsworthy_page+1) * 5)
				maxRows = 5;
			else
				maxRows = newsworthy.length % 5;
	
			for (i = 0; i < 5; i++) {
				var newBox = i + (5 * newsworthy_page);
				var currentBox = $('.newsworthy_item')[i];
				var newsworthyLink = '#';
				
				if (i < maxRows) {
					if (newsworthy[newBox].link != 'none')
						newsworthyLink = newsworthy[newBox].link;
						
					$(currentBox).html('<input type="hidden" value="' + newsworthyLink +'" /><img id="newsworthy_' + newsworthy[newBox].id + '" src="/_images/homepage/' + newsworthy[newBox].id + '.jpg" /><span class="newsworthy_title">' + newsworthy[newBox].title + '</span><br /><span class="newsworthy_blurb">' + newsworthy[newBox].blurb + '</span>');
				}
				else
					$(currentBox).html('<p>&nbsp;</p>');
			}
	
			if (newsworthy_page+1 == totalPages)
				$('#_rightArrow img').hide();
			else if (newsworthy_page == 0)
				$('#_leftArrow img').hide();
		});
	
		$('.newsworthy_item').click(function() {
			window.location = $(this).children()[0].value;
		});
	}
	
	if ($('#renovations').html()) {
		$('#renovations').dialog({
			title:			"We're renovating!",
			modal:			true,
			autoOpen:		false,
			width:			500,
			height:			250
		});
		
		$('a[target!="_blank"][href$=".htm"][href^="/"]').each(function() {
			var link = $(this).attr('href');
			$(this).attr('href','#');
			$(this).click(function() {
				$.ajax({
					url:		"/_include/renoCookie.cfm",
					data:		{ajax:true},
					success:	function() {
						openDeprecatedLink(link);
					}
				});
			});
		});
	}
	
	function openDeprecatedLink(link) {
		$('#renovations').dialog('option','buttons',{
			"Ok":function() {
				window.location = link;
			}
		});
		$('#renovations').dialog('open');
	}

	var val = $('#v').val();

	$('#searchBox').click(function() {
		$(this).val('');
	});
	$('#searchBox').focus(function() {
		$(this).val('');
	});
	$('#searchBox').blur(function(e) {
		$(this).val('WHAT ARE YOU LOOKING FOR?');
	});


	$.ajax({
		url:			'/_include/searchTags.cfm',
		dataType:		'json',
		data:			{ajax:true},
		success:		function(data) {
			availableSearchTags = data;

			$('#searchBox').autocomplete({
				source: availableSearchTags,
				minLength:	3,
				focus:	function(event, ui) {
					$('#searchBox').val(ui.item.label);
					return false;
				},
				select: function(event, ui) {
					$('#searchBox').val(ui.item.label);
					$('#searchBox-id').val(ui.item.label);
					$('#searchBox-description').html(ui.item.desc);
					$.ajax({
						url:		'/_include/searchTags.cfm',
						dataType:	'json',
						data:		{ajax:true,hit:ui.item.value},
						success:	function() {
							window.location = ui.item.link;
							return false;
						}
					});
					
				}
			})
			.data('autocomplete')._renderItem = function(ul, item) {
				return $('<li class="searchTag_item"></li>')
					.data('item.autocomplete', item)
					.append('<a><span class="search_label">' + item.label + '</span><br /><span class="search_description">' + item.desc + '</span></a>')
					.appendTo(ul);
			}
		}
	});

	$('#datepicker').datepicker({
		minDate:	new Date(),
		onSelect:	function(dateText, inst) {
			$.ajax({
				url:		'/daySheet.cfm',
				data:		{date:dateText,ajax:true},
				dataType:	'html',
				success:	function(data) {
					$('#calendarDialog').html(data)
					.dialog({
						modal:			true,
						dialogClass:	'calendarDialog',
						title:			"What's Happening on " + dateText,
						minWidth:		600
					});
					$('#calendarDialog button').button();
					$('#pricesLink').click(function() {
						if ($('#admissionPrices').is(':visible'))
							$('#admissionPrices').fadeOut();
						else 
							$('#admissionPrices').fadeIn();
					});
					$('#emailButton').click(function() {
						$('#emailForm').show();
						$('#emailAddress').focus();
					});
					$('#emailForm_GoButton').click(function() {
						if ($('#emailAddress').val().length > 5) {
							$.ajax({
								url:			'/_include/email_daySheet.cfm',
								data:			{ajax:true,email:$('#emailAddress').val(),date:dateText},
								dataType:		'json',
								type:			'post',
								error:			function() {
									$('#emailForm').append('<p id="warning" style="color: red;">We had a problem sending you the information.  Please try again in a few moments.');
									setTimeout($('#warning').fadeOut(), 6000);
								},
								success:		function(response) {
									if (response.success) {
										$('#calendarDialog').empty();
										$('#calendarDialog').html('<h1 style="height: 100%; width: 100%; padding: auto; text-align: center; color: green;">Email sent!</h1>');
									}
									else
										$('#emailForm').append('<p id="warning" style="color: red;">We had a problem sending you the information.  Please try again in a few moments.');
								}
							});
						}
					});
					$('#printButton').click(function() {
						window.location = '/daySheet.cfm?date=' + dateText;
					});
					$('.ui-dialog :button').blur();
				}
			});
		},
	});

	$('#calendar_button').click(function() {
		$('#datepicker').datepicker('show');
	});

	if ($('#map_canvas').length > 0) {
		initializeMap();
	}

	var name = $("#name"),
	email = $("#email"),
	email2 = $("#email2"),
	message = $("#message"),
	museum_staff = $("#museum_staff"),
	webpage_link = $("#webpage_link"),
	allFields = $([]).add(name).add(email).add(email2).add(message).add(museum_staff).add(webpage_link),
	tips = $(".validateTips");

	function updateTips(t) {
		tips
			.text(t)
			.addClass('ui-state-highlight');
		setTimeout(function() {
			tips.removeClass('ui-state-highlight', 1500);
		}, 500);
	}

	function checkLength(o,n,min,max) {
		if (o.val().length > max || o.val().length < min) {
			o.addClass('ui-state-error');
			updateTips("Length of " + n + " must be between "+min+" and "+max+".");
			$('#'+n).focus();
			return false;
		} else {
			return true;
		}
	}

	function checkRegexp(o,regexp,n) {
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass('ui-state-error');
			updateTips(n);
			return false;
		} else {
			return true;
		}
	}

	function compareEmails(e1, e2) {
		if (e1.val() != e2.val()) {
			e1.addClass('ui-state-error');
			e2.addClass('ui-state-error');
			updateTips("The email addresses provided do not match.  Without a correct email address we cannot contact you.");
			return false;
		} else {
			return true;
		}

	}

	$('.contactLink').click(function() {
		$('#contact_contentOwner').dialog('option', 'title', 'Contact the ' + $(this).html());
		$('#museum_staff').val($(this).html());
		if ($(this).attr('id') == 'forceLink') {
			$('#includeLink_checkbox').remove();
			$('#includeLink_text').remove();
			$('#webpage_link').val($('#lastPage_link').val());
		}
		$('#contact_contentOwner').dialog('open');
	});

	$("#contact_contentOwner").dialog({
		autoOpen:	false,
		height:		600,
		width:		550,
		modal:		true,
		title:		'Contact the ' + $('#museum_staff').val(),
		buttons: {
			'Send message': function() {
				sendMessage();
			},
			'Cancel': function() {
				resetContactForm();
			}
		},
		close: function() {
			museum_staff = $('#museum_staff').val();
			allFields.val('').removeClass('ui-state-error');
			$('#museum_staff').val(museum_staff);
		}
	});

	function sendMessage() {
		var bValid = true;
		allFields.removeClass('ui-state-error');

		bValid = bValid && checkLength(name,"name",3,30);
		bValid = bValid && checkLength(email,"email",6,80);
		bValid = bValid && checkLength(email2,"email2",6,80);
		bValid = bValid && checkLength(message,"message",5,1000);

		// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
		bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"please check your email address to ensure it is correct, eg. johndoe@companyname.com");
		bValid = bValid && checkRegexp(email2,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"please check your email address to ensure it is correct, eg. johndoe@companyname.com");

		bValid = bValid && compareEmails(email, email2);

		if (bValid) {
			try {
				$.post('/_include/staffMailer.cfm', $('#staff_contact').serialize(), function() {
					$('#contactDialog_response').html('<p style="margin: 250px 0px;">Message sent!  Please allow 48 hours for a response.</p>');
					$('#contact_contentOwner').dialog('option', 'buttons', {"OK": function() {
							resetContactForm();
						}
					});
					$('#contact_contentOwner table, p.validateTips').effect('blind');
				});
			} catch (e) {
				alert("Our apologies!  Email could not be sent.");
			}
		}
	}

	function resetContactForm() {
		$('#name').val('');
		$('#email').val('');
		$('#email2').val('');
		$('#email2text').html('Re-enter Email');
		$('#includeLink_checkbox').attr('checked', false);
		$('#includeLink_text').html('Include link to this webpage with message?');
		$('#message').html('');
		$('#contactDialog_response').html('');
		$('#contact_contentOwner').dialog('option','buttons', {
			'Send message': function() {
				sendMessage();
			},
			'Cancel':		function() {
				resetContactForm();
			}
		});
		$('#contact_contentOwner').dialog('close');
	}

	$('#email2').blur(function() {
		if ($('#email').val() != $('#email2').val()) {
			$('#email2text').html('email addresses do not match!');
			$('#email2text').addClass('alert');
			$('#email2text').effect('pulsate', function() {
				$('#email2').focus();
			});
		}
		else {
			$('#email2text').removeClass('alert');
			$('#email2text').html('<span style="color: green;">Emails match!</span>');
		}
	});

	$('#includeLink_checkbox').click(function() {
		if (this.checked) {
			$('#includeLink_text').html('<strong>link attached to message</strong>');
			$('#webpage_link').val(window.location.href);
		}
		else {
			$('#includeLink_text').html('Include link to this webpage with message?');
			$('#webpage_link').val('');
		}
	});

	if ($('#contactUs_container').html()) {
		$('div.activeDiv select').change(function() {
			if ($(this).val() != 0)
				contactUs_changeTo($(this).val());
		});
	}
	
	function contactUs_changeTo(newActiveDiv) {
		$('.activeDiv').hide();
		$('.activeDiv').removeClass('activeDiv');
		$('div#' + newActiveDiv).addClass('activeDiv').fadeIn();
		$('#' + newActiveDiv + ' select').change(function() {
			contactUs_changeTo($(this).val());
		});
	}
	
	$('#contactUs_container button').button();
	$('#contactUs_container button').click(function() {
		$('#contactUs_container select').val('0');
		$('#contactUs_container div').hide();
		$('#general').addClass('activeDiv').show();
	});
	
	$('#past_year_selector').change(function() {
		window.location = '?year=' + $(this).val();
	});
});

function prepareHeadliners() {
	$('#counter_end').html(headliners.length);

	$(headliners).each(function(i, element) {
		$('#billboard_viewAll').append('<img id="billboard_' + (i+1) + '" src="/_images/homepage/' + element.id + '.jpg" title="' + headliners[i].title + '\n' + headliners[i].dates + '" />');
	});
	$('#billboard_viewAll').position({
		my:		"center bottom",
		at:		"center top",
		of:		$('#scroller'),
		offset:	"68 -60"
	});
/*
	$('#billboard_viewAll').position({
		my:		"right bottom",
		at:		"left top",
		offset:	"150 -80",
		of:		$('#nextArrow')
	});
*/
	$('#billboard_viewAll img').each(function(i, element) {
		$(element).click(function() {
			$('#billboard_viewAll').hide();
			headlinerMove(eval(i));
		});
	});

	$('#viewAll').click(function() {
		if ($('#billboard_viewAll').is(':hidden')) {
			window.clearTimeout(timeout);
			autoRotate = false;
			$('#billboard_viewAll').fadeIn();
		}
		else
			$('#billboard_viewAll').fadeOut();
	});

	headlinerMove(0);
}

function headlinerMove(move) {
	//	hide previews
	$('#billboard_viewAll').hide();

	if (move == 'b') {
		headlinerActive--;
		window.clearTimeout(timeout);
	}
	else if (move == 'n') {
		headlinerActive++;
		window.clearTimeout(timeout);
	}
	else
		headlinerActive = move;

	if (headlinerActive == $('#counter_end').html()) {
		//	end of run
		headlinerActive--;
		return false;
	}
	else if (headlinerActive == -1) {
		//	at beginning
		headlinerActive = 0;
		return false;
	}
	else {
		$('#billboard').animate({opacity: 0}, 'slow', function() {
			var clickURL = '#';
			
			if (headliners[headlinerActive].link)
				clickURL = headliners[headlinerActive].link;
			else
				clickURL = '/events/exhibits/' + headliners[headlinerActive].type + '.cfm?id=' + headliners[headlinerActive].id;

			if (headliners[headlinerActive].id == 7)
				clickURL = 'http://www.infrastructure.alberta.ca/3654.htm';

			var thisImage = '/_images/homepage/' + headliners[headlinerActive].id + '.jpg';

			$(this).css('background','url(' + thisImage + ') no-repeat');
			
			if (headliners[headlinerActive].soon == 'true') {
				$('#clickableWindow').css('background','url(/_images/comingSoon.png) top left no-repeat');
				$('#clickableWindow').show();
			}
			else
				$('#clickableWindow').css('background','none');

			//	show all preview images, but then hide current preview image
			$('#billboard_viewAll img').show();
			$('#billboard_viewAll img[src="' + thisImage + '"]').hide();

			$('#clickableWindow').click(function() {
				window.location = clickURL;
			});
			
			if (headliners[headlinerActive].title.length > 30)
				$('#scroller_title').css('font-size','22px');
			else
				$('#scroller_title').css('font-size','24px');
			
			$('#scroller_title').html(headliners[headlinerActive].title).click(function() {
				window.location = clickURL;
			});
				
			$('#scroller_dates').html(headliners[headlinerActive].dates).click(function() {
				window.location = clickURL;
			});
			$('#counter_status').html(headlinerActive+1);
			$(this).animate({opacity: 1}, 'slow', function() {
				if (autoRotate)
					timeout = window.setTimeout("headlinerMove('n')", autoRotateTime);
			});
		});
	}
}

function externalLink_options(googleCache_date, googleCache_Url, caller) {
	$(this).attr('href','#');
	go2Google = confirm("This external link appears to be down, but there is a Google cached version dated " + googleCache_date + ".  Would you like to see that instead?");
	if (go2Google)
		window.location = googleCache_Url;
		
	return false;
}

