/**
 * @package WordPress
 * @subpackage lfe_Theme
 */

$(function () {
	
	Lambdas.init();

});

$(window).load(function() {
  $('html, body').scrollTop(0);    
});

var _current = '',
	_map = null,
	_marker = null;

var Home = (function () {

  function _initSpotlight() {
    var spotlight = $('#spotlight div.spotlight-slider');

    window.onload = function() {
      var height = 0, postHeight = 0;
      spotlight.find('div.spotlight-list, div.post.full').each(function() {
        postHeight = $(this).height();
        if (postHeight > height) {
          height = postHeight;
        }
      });
  
      $('#spotlight').height(height + spotlight.position().top);
    }

    spotlight
      .delegate('div.spotlight-list div.post', 'click', function() {
        spotlight.find('div.post.full').hide().filter('[data-id=' + $(this).data('id') + ']').show();
        spotlight.addClass('expand');
      })
      .delegate('div.post.full', 'click', function() {
        spotlight.removeClass('expand');
      })
      .delegate('a', 'click', function(e) {
        e.stopPropagation();
      });
  }

	return {
		init: function () {
			$('#slider').nivoSlider({
				directionNav: false,
				pauseTime: 4000,
				slices: 10
			});

      _initSpotlight();
		}
	};
	
}());

var Lambdas = (function () {
	
	return {
		init: function () {
			_current = $('body').attr('class');
			_map = null;
			
			if (!_current) {
				$('body').addClass('home');
			}
	
			Navigation.init();
			Utilities.init();
			
			switch (_current) {
				case 'about':
				case 'programs':
					break;
        case 'spotlight':
          Spotlight.init(_current);
          break;
				case 'membership':
					Membership.init();
					break;
				case 'media':
				  Media.init();
				  break;
				case 'contact':
					Contact.init();
					break;
				default:
					Home.init();
					break;
			}
			
			$('#tabs > div ul').addClass('list');
		}
	};
	
}());

var Spotlight = (function () {

  return {
    init: function (current) {
      var spotlight = $('#spotlight');
  
      spotlight.delegate('div.spotlight-list div.post', 'click', function() {
        spotlight.find('div.post.active').removeClass('active');
        spotlight.find('div.post.detail').hide().filter('[data-id=' + $(this).data('id') + ']').show();
        $(this).addClass('active');
      });

      if (current === 'spotlight' && window.location.hash) {
        window.onload = function() {
          spotlight.find('div.spotlight-list div.post[data-id=' + window.location.hash.substr(1) + ']').click();
        };
      } else {
        spotlight.find('div.spotlight-list div.post:first').click();
      }
    }
  };

}());

var Membership = (function () {

	return {
		init: function () {
			var script = '<scr' + 'ipt type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&callback=Membership.mapsLoaded" async="true"></scr' + 'ipt>';
			$('script:last').before(script);

			$('#chapter-search a').click(function () {
				$(this).parent().submit();
				return false;
			});
			
			$('#chapter-search').submit(function () {
				$('#results').html('');
				
				var geocoder = new google.maps.Geocoder();
				geocoder.geocode({ address: $(this).find(':text').val() }, function(results, status) {
					if (status == google.maps.GeocoderStatus.OK) {
						var location = results[0].geometry.location;
						console.log(location);
						$.ajax({
							url: '/wp-admin/admin-ajax.php',
							type: 'POST',
							dataType: 'json',
							data: 'action=lphie_chapter_search&lat=' + location.lat() + '&lon=' + location.lng(),
							success: function(data) {
								var content = '<p>There are <strong>' + data.length + '</strong> chapter(s) located nearby.' + (data.length === 0 ? ' Please try searching again.' : '');
								
								if (data.error) {
									content = '<p>' + data.error + '</p>';
								}
								else if (data.length > 0) {
									content += '<ul class="list">';
									for (var i = 0; i < data.length; i++) {
										content += '<li>' +
											'<a href="' + (data[i].url ? data[i].url : '/') + '" target="_blank">' + data[i].chapter + '<span>' + data[i].distance + ' miles away</span></a>' +
										'</li>';
									}
									content += '</ul>';
								}
								
								$('#results').html(content);
							}															
						});

						if (_marker) {
							_marker.setMap(null);
						}
						_marker = new google.maps.Marker({
							map: _map, 
							position: location
						});
						
						_map.panTo(location);
						_map.setZoom(7);
					} else {
						alert("Geocode was not successful for the following reason: " + status);
					}
				});
				
				return false;
			});
		},
		mapsLoaded: function () {
	    	_map = new google.maps.Map($('#map')[0], {
	    		zoom: 3,
	    		center: new google.maps.LatLng(39.50, -98.35),
	    		mapTypeId: google.maps.MapTypeId.ROADMAP
	    	});
	    	
	    	var layer = new google.maps.KmlLayer(_siteUrl + '/wp-admin/admin-ajax.php?action=lphie_chapter_rss');
	    	layer.setMap(_map);
	    	
			google.maps.Map.prototype.clearMarkers = function () {
			    for (var i = 0; i < this.markers.length; i++){
			        this.markers[i].setMap(null);
			    }
			    this.markers = new Array();
			};
		}
	};
	
}());

var Media = (function () {

  return {
    init: function () {
      $('#page a.gallery').fancybox({
        overlayColor: '#000',
        overlayOpacity: 0.6,
        padding: 1
      });
    }
  };

}());

var Contact = (function () {

	function _validate() {
		var valid = true,
			parameters = '';
		
		$('#contact input:text, #contact textarea').removeClass('error').each(function (index, element) {
			parameters += '&' + $(element).attr('name') + '=' + $(element).val();
			if ($.trim($(element).val()) === '') {
				$(element).addClass('error');
				valid = false;
			}
		});
		
		return !valid ? false : parameters;
	}

	return {
		init: function () {
			$('#contact a.button').click(function () {
				$('#contact').submit();
				return false;
			});
			
			$('#contact').submit(function () {
				var valid = _validate();
				if (valid) {
					var button = $(this).find('a.button').text('Sending').addClass('disabled');
					$('#status').slideUp();
					$('#loading').show();
					
					$.ajax({
						url: '/wp-admin/admin-ajax.php',
						type: 'POST',
						dataType: 'json',
						data: 'action=lphie_contact' + valid,
						success: function (data) {
							button.text('Send Message').removeClass('disabled');
							$('#loading').hide();
							$('#status').text(data.error ? data.error : 'Thank you for contacting us! We will be in touch as soon as possible.').slideDown();
							return false;
						}
					});
				}

				return false;
			});
		}
	};
	
}());

var Navigation = (function () {

	var _menuTimer = null, _list, _offset;

	function _checkTarget(e) {
		e.stopPropagation();
		if ($(e.target).parents('div.drop.persist').size() || $(e.target).siblings('div.drop.persist').is(':visible')) {
			return false;
		}
		$('div.drop.persist').fadeOut();
	}
	
	return {
		init: function () {
			$('a[href=/' + _current.toLowerCase() + ']').addClass('active');
			$('#search input:text').focus(function () { $(this).parent().addClass('focus'); }).blur(function () { $(this).parent().removeClass('focus') });
	
			$('#navigation li').hover(function () {
				var drop = $(this).find('.drop:not(.persist)');
				_menuTimer = setTimeout(function () {
					drop.stop(true, true).fadeIn();
				}, 200);
			}, function () {
				clearTimeout(_menuTimer);
				$(this).find('.drop:not(.persist)').stop(true, true).fadeOut();
			});
			
			// Problem
			$('.drop.persist').parent().click(function (e) {
				if (_checkTarget(e) === false) return false;
				$(this).find('.drop.persist').fadeToggle(200).find('input:text:first').focus();
				return false;
			});
			
			$(window).click(function (e) {
				return _checkTarget(e);
			});

			_list = $('#tabs > ul'), _offset = _list.offset();
			if (_list[0]) {
				$(window).scroll(function () {
					_list.toggleClass('fixed', $(window).scrollTop() > (_offset.top - 40));
				});
			}
		}
	};

}());

var Utilities = (function () {

	/*
	 * jQuery hashchange event - v1.3 - 7/21/2010
	 * http://benalman.com/projects/jquery-hashchange-plugin/
	 * 
	 * Copyright (c) 2010 "Cowboy" Ben Alman
	 * Dual licensed under the MIT and GPL licenses.
	 * http://benalman.com/about/license/
	 */
	(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);
	$.fn.tabs=function(d){function e(f){a=!f?b:f;c.children('ul').find('a.active').removeClass('active').end().find('a[href='+a+']:last').addClass('active').end().end().children('div').hide().end().children(a).show();typeof d.onChanged==='function'&&d.onChanged()}var c=null,b='',a='';return this.each(function(){c=$(this).children('div').hide().end();b=!window.location.hash?'#'+c.children('div:first').attr('id'):window.location.hash;e(b);$(window).hashchange(function(){e(window.location.hash)})})};
	$.fn.fader=function(){return this.each(function(){$(this).find('span').animate({opacity:0},2E3).hover(function(){$(this).stop().animate({opacity:1},600)},function(){$(this).stop().animate({opacity:0},600)})})};

	return {
		init: function () {
			$('#crest').fader();
			$('#page div.tabs').tabs({
				onChanged: function () {
					$('html, body').scrollTop(0);
					if (_map && $('#map').is(':visible')) {
						google.maps.event.trigger(_map, 'resize');
						var location = new google.maps.LatLng(39.50, -98.35);
						_map.panTo(location);
						_map.setZoom(3);
					}
				}
			});
		}
	};

}());

