/* Author: Nick DiMatteo

*/

/*
function flip() {
	if ($('#contact').hasClass('section-active')) {
		$('#banner').addClass('black');
	} else {
		$('#banner').removeClass('black');
	}
};
*/





jQuery(function ($) {

	// Register each section as a waypoint.
	$('.section').waypoint({ offset: '25%' });
	
	// The same for all waypoints
	$('body').delegate('.section', 'waypoint.reached', function(event, direction) {
		var $active = $(this);
		
		if (direction === "up") {
			$active = $active.prev();
		}
		if (!$active.length) $active.end();
		
		$('.section-active').removeClass('section-active');
		$active.addClass('section-active');
		
		$('.active').removeClass('active');
		$('a[href=#'+$active.attr('id')+']').addClass('active');
		
		//store active section value
		var sectionHash = 'a[href=#'+$active.attr('id')+']';
		
		//change the hash when you get to the section
		//$.address.value($(sectionHash).attr('href').replace(/^#/, ''));
		
		//if home, just display normal title
		if ($(sectionHash).html() == '') {
			$.address.title('Kevin Dare Foundation');
		}
		else //otherwise show section title
		{
			$.address.title('Kevin Dare Foundation | ' +$(sectionHash).html().replace("&amp;", "&"));
		}
		//flip();
	});
	
	// Negates the flash of non-active nav.
	$('body > header nav a').click(function() {
		$(this).addClass('active');
	}).eq(0).addClass('active');
	
	// Wicked credit to
	// http://www.zachstronaut.com/posts/2009/01/18/jquery-smooth-scroll-bugs.html
	var scrollElement = 'html, body';
	$('html, body').each(function () {
		var initScrollTop = $(this).attr('scrollTop');
		$(this).attr('scrollTop', initScrollTop + 1);
		if ($(this).attr('scrollTop') == initScrollTop + 1) {
			scrollElement = this.nodeName.toLowerCase();
			$(this).attr('scrollTop', initScrollTop);
			return false;
		}    
	});
	
	// Smooth scrolling for internal links
	$("a[href^='#']").click(function(event) {
		event.preventDefault();
		
		var $this = $(this),
		target = this.hash,
		$target = $(target);
		
		$(scrollElement).stop().animate({
			'scrollTop': $target.offset().top
		}, 1000, 'easeInOutExpo');
		
	});
	
});

$(document).ready(function(){

		$(document).bind(wtf);

		//check for hash and navigate to that section if present
		var hash = document.location.hash.replace(/^#\//, '');
		if(hash) {
		$('nav a[href="#'+hash+'"]').trigger('click');
		}
	
	// Run Matt Kersley's jQuery Responsive menu plugin (see plugins.js)
	if ($.fn.mobileMenu) {
		$('ol#id').mobileMenu({
			switchWidth: 768,                   // width (in px to switch at)
			topOptionText: 'Choose a page',     // first option text
			indentString: '&nbsp;&nbsp;&nbsp;'  // string for indenting nested items
		});
	}

	// Run Mathias Bynens jQuery placeholder plugin (see plugins.js)
	if ($.fn.placeholder) {
		$('input, textarea').placeholder();		
	}
	
	(function () {
		parallaxSite.create();
	}());
	initialize();
});


//Change Page Title on browser back button press
$.address.externalChange(function() {
	var hash = document.location.hash.replace(/^#\//, '');
	$('nav a[href="#'+hash+'"]').trigger('click');
	var lastPageTitle = 'Kevin Dare Foundation | ' + $('nav a[href="#'+hash+'"]').html().replace("&amp;", "&");
	if(hash) {
	$.address.title(lastPageTitle);
	}
	else if (lastPageTitle == '') {
		$.address.title('Kevin Dare Foundation');
	}
	else //account for no hash
  {
  $.address.title('Kevin Dare Foundation');
  }
});

//change page title on nav click & replace with hash
$('nav a').click(function() { 
	var pageTitle = 'Kevin Dare Foundation | ' + $(this).html().replace("&amp;", "&");
	$.address.value($(this).attr('href').replace(/^#/, ''));
	if ($(this).html() == '') {
		$.address.title('Kevin Dare Foundation');
	}
	else
	{
		$.address.title(pageTitle);
	}
});


$(document).ready(function()
{
	$('.content').each(
		function()
		{
			$(this).jScrollPane(
				{
					showArrows: $(this).is('.arrow')
				}
			);
			var api = $(this).data('jsp');
			var throttleTimeout;
			$(window).bind(
				'resize',
				function()
				{
					if ($.browser.msie) {
						// IE fires multiple resize events while you are dragging the browser window which
						// causes it to crash if you try to update the scrollpane on every one. So we need
						// to throttle it to fire a maximum of once every 50 milliseconds...
						if (!throttleTimeout) {
							throttleTimeout = setTimeout(
								function()
								{
									api.reinitialise();
									throttleTimeout = null;
								},
								50
							);
						}
					} else {
						api.reinitialise();
					}
				}
			);
		}
	)

});

//bind keys to navigate site
var pressedKeys = {};
var wtf = {
	'keyup': function (e) {
		if (pressedKeys[e.which])
			return;
			pressedKeys[e.which] = true;
		var keyCode = e.keyCode || e.which,
				key = {left: 37, up: 38, right: 39, down: 40};
	
		switch (keyCode) {
			case key.left:
			case key.up:
				$(document).find('#nav-main li a.active').parent().prev('li').find('a').trigger('click');
			break;
			
			case key.right:
			case key.down:
				$(document).find('#nav-main li a.active').parent().next('li').find('a').trigger('click');
			break;
		}
	},
	'keydown': function (e) {	
		delete pressedKeys[e.which];
		var keyCode = e.keyCode || e.which,
				key = {left: 37, up: 38, right: 39, down: 40 };
				
		switch (keyCode) {
			case key.up:
			case key.down:
				e.preventDefault();
			break;
		}
	}
};

function initialize() {
				var location = new google.maps.LatLng(40.813485, -77.829300);
        var myOptions = {
          center: location,
          zoom: 15,
          scrollwheel: false,
          mapTypeControl: false,
			    panControl: false,
			    zoomControl: false,
			    scaleControl: false,
			    streetViewControl: false,
          mapTypeId: 'satellite',
        };
        
        //create map
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        
        //create controls
        map.controls[google.maps.ControlPosition.TOP_RIGHT].push(new ZoomPanControl(map));
        
        //custom overlay
				var texturedMapType = new google.maps.ImageMapType({
				    getTileUrl: function(tileCoord, zoom, ownerDocument)
				    {
				        //image src
				        return '/img/bg.map-overlay.png';
				    },
				    isPng: true,                    
				    tileSize: new google.maps.Size(256, 256)
				});
				
				//Add a new layer between the map and the markers and render tiles here
				map.overlayMapTypes.push(null);
				map.overlayMapTypes.setAt(0, texturedMapType);
				
				//Add a marker and modal box
				var image = new google.maps.MarkerImage('/img/icn.map.png',
	      //Marker size
	      new google.maps.Size(90, 90),
	      //Origin
	      new google.maps.Point(0,0),
	      //Anchor
	      new google.maps.Point(45, 45));
	      
				var marker = new google.maps.Marker({
         map: map,
         draggable: false,
         position: new google.maps.LatLng(40.815485, -77.829159),
         visible: true,
         icon: image
        });
        
        //Create the modal box
        var boxText = document.createElement("div");
        boxText.style.cssText = "margin-bottom: 20px; background: #fff; padding: 80px 0 30px 0;";
        boxText.innerHTML = "<h2>Contact</h2><div class=\"container clearfix\"><h3>The Kevin Dare Foundation</h3><p>366 Walker Drive, Suite 100<br />State College, PA 16801</p><p><b>email:</b> <a href=\"mailto:aszefi@kevindare.com\">aszefi@kevindare.com</a><br /><b>phone:</b> 814.231.2249<br /><b>fax:</b> 814.235.3500</p></div>";
                
        var myOptions2 = {
                 content: boxText
                ,alignBottom: true
                ,disableAutoPan: false
                ,maxWidth: 0
                ,pixelOffset: new google.maps.Size(-250, -50)
                ,zIndex: null
                ,boxStyle: { 
                  width: "500px",
                  background: "transparent url('/img/icn.tooltip.png') bottom center no-repeat"
                 }
                ,closeBoxMargin: "10px"
                ,closeBoxURL: "/img/icn.close.png"
                ,closeBoxClass: "close"
                ,infoBoxClearance: new google.maps.Size(100, 100)
                ,isHidden: false
                ,pane: "floatPane"
                ,enableEventPropagation: false
        };
        
        //Allow icon to be clicked to open/close modal window
        google.maps.event.addListener(marker, "click", function (e) {
					ib.open(map, this);
				});

        var ib = new InfoBox(myOptions2);
        ib.open(map, marker);
};





function CreateElement(tagName, properties) {
    var elem = document.createElement(tagName);
    for (var prop in properties) {
        if (prop == "style")
            elem.style.cssText = properties[prop];
        else if (prop == "class")
            elem.className = properties[prop];
        else
            elem.setAttribute(prop, properties[prop]);
    }
    return elem;
}

function ZoomPanControl(map) {
    this.map = map;
    var t = this;
    var zoomPanContainer = CreateElement("div", { 'style': "position: relative; padding: 20px;" });
    
    //Map Controls
    var zoomContainer = CreateElement("div", { 'class':'map-controls' });
    zoomPanContainer.appendChild(zoomContainer);
    div = CreateElement("div", {'title': 'Zoom in', 'class':'zoom-in' });
    google.maps.event.addDomListener(div, "click", function() { t.zoom(ZoomDirection.IN); });
    zoomContainer.appendChild(div);
    div = CreateElement("div", {'title': 'Zoom out', 'class':'zoom-out' });
    google.maps.event.addDomListener(div, "click", function() { t.zoom(ZoomDirection.OUT); });
    zoomContainer.appendChild(div);
    div = CreateElement("div", {'title': 'Center', 'class':'center-map' });
    google.maps.event.addDomListener(div, "click", function() { map.setCenter(new google.maps.LatLng(40.815485, -77.829159)); map.panBy(100,100); });
    zoomContainer.appendChild(div);
    
    
    return zoomPanContainer;
}

/** @param {ZoomDirection} direction */
ZoomPanControl.prototype.zoom = function(direction) {
    var zoom = this.map.getZoom();
    if (direction == ZoomDirection.IN && zoom < 19)
        this.map.setZoom(zoom + 1);
    else if (direction == ZoomDirection.OUT && zoom > 1)
        this.map.setZoom(zoom - 1);
}

/** @enum */
var ZoomDirection = {
    IN: 0,
    OUT: 1
}
