// default

var RecaptchaOptions 	= { theme : 'clean' };

var browser				= $(window);

//
$.postJSON = function (url, data, callback) {
	$.post(url, data, callback, 'json');
};

//
$(function(){
	
	// slide up/down navigation
	$('#nav>ul>li>a').each(function(){
		$(this).bind('click', function(){
			$('#nav>ul>li>ul').slideToggle();
			return false;
		});
	});
	
	// slide up navigation follow href
	$('#nav>ul>li>ul>li>a').each(function(){
		$(this).bind('click', function(){
			var url = $(this).attr('href');
			$('#nav>ul>li>ul').slideUp(function(){ window.location = url; });
			return false;
		});
	});
	
	// event tracker for outgoing links/file downloads
	if(typeof _gaq != "undefined"){
		$('a').each(function(){
			var path;
			
			if(path = $(this).attr('href')){
				var outgoing 	= /^(http|https)/i;
				var ext 		= /[^/].(?:doc|eps|jpg|jpeg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3|mp4)$/i;
				
				if (path.match(outgoing) && !path.match(document.domain) ) {
					$(this).click(function(){
						_gaq.push(['_trackEvent', 'Link', 'Outgoing', $(this).attr('href')]);
					});
				} else if(path.match(ext)){
					$(this).click(function(){
						_gaq.push(['_trackEvent', 'File', 'Download', $(this).attr('href')]);
					});	
				}
			}
		});
	}
	
	//
	$('ul.list>li:not(.no-click)').bind('click', function(){
		var url = $(this).find('a:eq(0)').attr('href')
		if(typeof url != "undefined"){
			window.location = url;
		}
	});
	
	// 
	$('input').focus(function(){
		if($(this).val() == $(this).attr('title')){ $(this).val(''); }
	}).blur(function(){
		if($(this).val() == ''){ $(this).val($(this).attr('title')); }
	});
	
	// forms
	$('#form').ajaxForm({
        beforeSubmit:  	function(formData, form, options){
							$('input.warning,textarea.warning,checkbox.warning,select.warning').removeClass('warning');
							$('.validate').slideUp();
							return true;
						}, 
        success:       	function(data, status, xhr, form){
							if(data.success == true){
								$('.validate>p').html(data.thank_you);
								$('.validate').slideDown();
								$('html, body').animate({ scrollTop: 200 }, 1000);
								form.slideUp();
							} else {
								$('.validate>p').html('');
								
								for (var i in data.error){
									$('.validate>p').append(data.error[i] + '<br />');
								}
								
								for (var i in data.error){
									$('[name=' + data.name[i] + ']').addClass('warning');
								}
								
								$('html, body').animate({ scrollTop: 200 }, 1000, function(){$('.validate').slideDown();});
								
								if(typeof Recaptcha != "undefined"){
									Recaptcha.reload();
								}
							}
						},
		type:			'post',
		dataType:		'json'
	});
	
	// newsletter
	$('#newsletter>form').ajaxForm({
		dataType		:	'json',
		beforeSubmit	:	function(){
								$('input.warning,textarea.warning,checkbox.warning,select.warning').removeClass('warning');
							},  
        success			:	function(response, status){
								if(response.success == true){
									$('#newsletter>form').fadeOut();
									$('#newsletter-msg>p').html(response.msg).parent('div').fadeIn();
								} else {
									$('#newsletter-email').addClass('warning');
									$('#newsletter-msg>p').html(response.msg).parent('div').fadeIn();
								}
							}
	});
	
	// billboard
	$('#billboard').cycle({ 
		fx:				'fade', 
		speed:			1000,
		timeout:		5000,
		pause:			0,
		pauseOnPagerHover: 1,
		pager: '.buttons',
		pagerAnchorBuilder: function(idx, slide) { 
                return '<li><a href="#">&nbsp;</a></li>';
        },
		updateActivePagerLink: function(container, slide) {
			$(container+'>li>a').removeClass('sel');
			$(container+'>li:eq('+slide+')>a').addClass('sel');	
		},
		cleartype:		1,
		cleartypeNoBg:	1
	 });
	
	// more
	$('.moreLink,.moreBtn').click(function(){
		$(this).siblings('.moreTxt').show('slow', function(){ $(this).css({'display':'inline'})});
		$(this).siblings('.moreBtn').hide();
	});
	
	//windowshade
	$('.windowshade').each(function(){
		$(this).find('.string').bind('click', function(){
			$(this).parent('p').siblings('.shade').slideToggle();
			return false;
		});
	});
	
	// internal filterning nav
	$('#internal-nav>ul>li.plus>a').bind('click', function(){
		$(this).parent('li').children('ul:eq(0)').slideToggle(function(){ $(this).parent('li').toggleClass('minus'); });
		return false;
	});
	
	// gallery
	browser.resize(function(){
		resizeFancyImages();
	});
	
	resizeFancyImages();
	
	$('a.fancy').fancybox({
		'centerOnScroll'	: true,
		'overlayColor'		: '#000000',
		'overlayOpacity' 	: 1,
		'title'				: this.meta,
		'titleShow'			: true,
		'titlePosition'		: 'outside',
		'opacity'			: true
	});
	
	// billboard gallery with thumbnails 
	$('#billboard.billboard-gallery').cycle({ 
    	fx:     'fade',
		activePagerClass: 'sel',
		pager:	'.thumbnails',
		pagerAnchorBuilder: thumbnailBuilder,
		updateActivePagerLink: thumbnailHighlight,
		pause:			0,
		pauseOnPagerHover: 1
	});
	
	//
	$('ul.select>a.dropdown').click(function(){
		if($.browser.msie && $.browser.version < 8){
			var contentOffset = $('#content').offset();
			var buttonOffset = $(this).offset();
			$(this).parent('ul').find('ul').css({position:'absolute',top: (buttonOffset.top - contentOffset.top + 29) + 'px', right: '-1px'});
		}
		$('.hover').not($(this).parent('ul')).removeClass('hover');
		$(this).parent('ul').toggleClass('hover');
		return false;	
	});
	
	$('ul.select>li>ul>li>a,body').click(function(){
		$('.hover').not('#select-search,#select-browse').removeClass('hover');
		return true;
	});
	
	$('ul.select>a.slide').click(function(){
		
		$('.hover').not($(this).parent('ul')).removeClass('hover');
		
		$(this).parent('ul').eq()
		
		if($('.hover').is($(this).parent('ul'))){
			$('div#select-slide').slideUp();
		} else {
			$($(this).attr('href')).show();
			$($(this).attr('href')).siblings('div').hide();
			$('div#select-slide').slideDown();
		}
		
		$(this).parent('ul').toggleClass('hover');
	
		return false;	
	});
	
	// calendar
	$('#prev_month>a').bind('click', function(){
		var date 	 = $('table.calendar:first').attr('data-date');
		var type 	 = $('table.calendar:first').attr('data-type');
		var audience = $('table.calendar:first').attr('data-audience');
		
		if(type != ''){ type = 'type:' + type +  '/'; }
		if(audience != ''){ audience = 'audience:' + audience +  '/'; }
		
		$.getJSON('/ajax/command:mini-cal/direction:previous/date:' + date + '/' + type + audience, function(data){
			if(data.success == true){
				$('table.calendar:first').before(data.html);
				$('table.calendar:last').remove()
			}
		})
		
		return false;
	});
	
	$('#next_month>a').bind('click', function(){
		var date 	 = $('table.calendar:last').attr('data-date');
		var type 	 = $('table.calendar:last').attr('data-type');
		var audience = $('table.calendar:last').attr('data-audience');
		
		if(type != ''){ type = 'type:' + type +  '/'; }
		if(audience != ''){ audience = 'audience:' + audience +  '/'; }
		
		
		$.getJSON('/ajax/command:mini-cal/direction:next/date:' + date + '/' + type + audience, function(data){
			if(data.success == true){
				$('table.calendar:last').after(data.html);
				$('table.calendar:first').remove();
			}
		})
		
		return false;
	});
	
	// map
	$('.map').each(function(){
		if (GBrowserIsCompatible()) {
			
			var zoom = 18;
			
			var lat = $(this).data('lat');
			var lng = $(this).data('lng');
			var loc_floor = $(this).data('floor');
			var loc_type = $(this).data('type');
			var loc_url = $(this).data('url');
			
			if(loc_type == 'building'){
				zoom = 16;
			}
			
        	map = new GMap2(this);
			map.setCenter(new GLatLng(lat, lng), zoom /*,G_SATELLITE_MAP*/);
			
			map.addControl(new GSmallZoomControl3D());
			
			//
			var icon_img = new GIcon(G_DEFAULT_ICON);
			icon_img.image = "/img/map/bpac-marker.png";
			
			marker = new GMarker(new GLatLng(lat, lng),{icon: icon_img});
			
			GEvent.addListener(marker, "click", function() {
				window.open(loc_url);
			});
			
			map.addOverlay(marker);
			
		}	
	});
	
	$('.side-map').each(function(){
		if (GBrowserIsCompatible()) {
			
			var zoom = 19;
			
			var lat = $(this).data('lat');
			var lng = $(this).data('lng');
			var loc_floor = $(this).data('floor');
			var loc_type = $(this).data('type');
			
			if(loc_type == 'building'){
				zoom = 18;
			}
			
        	map = new GMap2(this);
			map.setCenter(new GLatLng(lat, lng), zoom /*,G_SATELLITE_MAP*/);
			
			map.addControl(new GSmallZoomControl3D());
			
			var boundaries = new GLatLngBounds(new GLatLng(42.931109,-78.878501), new GLatLng(42.931712,-78.877418));
			
			if(loc_floor == '2'){
				floor_img = new GGroundOverlay("/img/map/bpac-second-floor-web.png", boundaries);
			} else {
				floor_img = new GGroundOverlay("/img/map/bpac-first-floor-web.png", boundaries);
			}

			//map.setUIToDefault();
			map.addOverlay(floor_img);
			
			//
			var icon_img = new GIcon(G_DEFAULT_ICON);
			icon_img.image = "/img/map/bpac-marker.png";
			
			marker = new GMarker(new GLatLng(lat, lng),{icon: icon_img});
			
			map.addOverlay(marker);
			
		}	
	});
	
	// title popup
	$('li.label-box').hover(function(){ 
	
		var offset = $(this).offset();
		var left_right = 0;
		var index_pos = $(this).index() + 1;
		
		if(index_pos % 4 == 0 || index_pos % 4 == 3){
			left_right = -262;
			$('#label>.arrow').addClass('right');
		} else {
			left_right = 147;
			$('#label>.arrow').removeClass('right');
		}
		
		$('#label>.text').html($(this).data('label'));
		$('#label').css({top: offset.top+10, left: offset.left + left_right}).stop(true,true).delay(1000).fadeIn(500);
	}, function(){ 
		$('#label').stop(true,true).fadeOut(250);
	});
	
	$('a.label-box-square').hover(function(){ 
	
		var offset = $(this).offset();
		var left_right = 0;
		var index_pos = $(this).index() + 1;
		
		left_right = 140;
		$('#label>.arrow').removeClass('right');
		
		$('#label>.text').html($(this).data('label'));
		$('#label').css({top: offset.top+10, left: offset.left + left_right}).stop(true,true).delay(1000).fadeIn(500);
	}, function(){ 
		$('#label').stop(true,true).fadeOut(250);
	});
	
	// today
	$('#hours-admission>.nav>.one').bind('click', function(){ $(this).siblings('li').removeClass('current'); $(this).addClass('current'); $('#holder>div:not(#hours)').slideUp(750, function(){ $('#hours').slideDown(750); }); return false; });
	$('#hours-admission>.nav>.two').bind('click', function(){ $(this).siblings('li').removeClass('current'); $(this).addClass('current'); $('#holder>div:not(#admission)').slideUp(750, function(){ $('#admission').slideDown(750); }); return false; });
	
	// back
	$('.back').bind('click', function(e){ e.preventDefault(); history.go(-1); return false;});
	
	// view all
	$('.view-all>a.expand').click(function(){
		$(this).parent('h6').slideUp();
		$(this).parent('h6').siblings('.hide').slideDown();
		return false;
	});
	
	//
	$('.user-content').anchor();
	
	//
	$('.purchase-code>form>input[type=image]').attr('src','/img/layout/buy.gif');
	
	//
	$('.hide').hide();
	$('.show').show();
	
	//
	$('img').bind('contextmenu',function(e){ e.preventDefault(); return false; }).bind('mousedown',function(e){ e.preventDefault(); return false; });
	
});

//
function thumbnailBuilder(idx, slide) {
	var imageLocation	= $(slide).find('img').attr('src');
	imageLocation = imageLocation.substring(52);
	
	return '<li id="thumb-'+idx+'"><a href="#"><img src="/image/?action=auto-crop&m_w=75&m_h=75&p=top_center&path=' + imageLocation + '" /></a></li>';
}

//
function thumbnailHighlight(container, slide) {
	$(container+'>li').removeClass('sel');
	$('#thumb-'+slide).addClass('sel');
}

//
function resizeFancyImages(){
	$('a.fancy').each(function(){
		$(this).attr('href', setQueryParam(setQueryParam($(this).attr('href'), 'm_w', ($(window).width() - 90)), 'm_h', ($(window).height() - 230)));
	});
}

//
function setQueryParam(uri, key, value) {
	try{
		if (!uri.match(/\?/)) uri += '?';
		if (!uri.match(new RegExp('([\?&])' + key + '='))) {
			if (!uri.match(/[&\?]$/)) uri += '&';
			uri += key + '=' + escape(value);
		} else {
				uri = uri.replace(new RegExp('([\?\&])' + key + '=[^&]*'), '$1' + key + '=' + escape(value));
		}
		return uri;
	} catch (e){
		
	}
}
