//global namespace
var PNC; if(!PNC) PNC={};
PNC.ui = {};

$.lazy('/javascripts/jquery.accordion.min.js','accordion');
$.lazy('/javascripts/jquery.cycle.js','cycle');
$.lazy('/javascripts/hoverintent.js','hoverIntent');
$.lazy("/javascripts/jquery.fancybox/jquery.fancybox-1.2.1.js", "fancybox");
$.lazy('/javascripts/jquery.blockui.js','block');
$.lazy('/javascripts/jquery.form.js','ajaxForm');
$.lazy('/javascripts/jquery.form.js','ajaxSubmit');

PNC.configs = {
	initiativesListHoverConfig :{  
     sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
     interval: 100, // number = milliseconds for onMouseOver polling interval    
     over: function() {
							$(this).prev(".image_caption_slider").animate({right: 0});
							$(this).prevAll(".image_fade_container").trigger("fadecolor");
						}, // function = onMouseOver callback (REQUIRED)    
     timeout: 500, // number = milliseconds delay before onMouseOut    
     out: function() {
						$(this).prev(".image_caption_slider").animate({right: "-508px"});
						$(this).prevAll(".image_fade_container").trigger("fadebw");
					}		 // function = onMouseOut callback (REQUIRED)    
		
	},
	newsletterSubscribeConfirmation: "<h1>THANKS!</h1><p>Your email {email} has been successfully subscribed to our mailing list!</p>"
}

PNC.ui.initAjaxSettings = (function() {
	$(document).ajaxSend(function(event, request, settings) {
	  if (typeof(PNC.AUTH_TOKEN) == "undefined") return;
	  // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
	  settings.data = settings.data || "";
	  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(PNC.AUTH_TOKEN);
	});
	jQuery.ajaxSetup({ 
	  	'beforeSend': function(xhr) {
			    xhr.setRequestHeader("Accept", "text/javascript,application/json");
			} 
	});
});

PNC.ui.popup = function(msg) {
  $("#wrapper").append($("<div id='dialog'>"));
  $("#dialog").html(msg).dialog({
		modal: true,
		width: 400
	});
}

PNC.ui.imageFader = {
	fadeToColor: function(el){
		if($(el).is(".image_fade_container"))
			el = el;
		else if($(el).is("li"))
			el = $(el).find(".image_fade_container");
		else
			el = $(el).parents(".image_fade_container");
		$(el).find(".color").animate({"opacity": 1});
	},
	
	fadeToBlackAndWhite: function(el){
		if($(el).is(".image_fade_container"))
			el = el;
		else if($(el).is("li"))
			el = $(el).find(".image_fade_container");
		else
			el = $(el).parents(".image_fade_container");
		$(el).find(".color").animate({"opacity": 0});
	}
}

PNC.ui.Map = function(address) {
	var map = new GMap2(document.getElementById("map"),{
	  size: GSize(600, 400) 
	});
	var geocoder = new GClientGeocoder();
	
	(function showAddress(address) {
	  geocoder.getLatLng(
	    address,
	    function(point) {
	      if (!point) {
	        alert(address + " not found");
	      } else {
					map.addControl(new GLargeMapControl());
	        map.setCenter(point, 13);
	        var marker = new GMarker(point);
	        map.addOverlay(marker);
					GEvent.addListener(marker, "click", function() {
						marker.openInfoWindowHtml(address);
					});
	        
	      }
	    }
	  );
	})(address);
	return map;
}

//app init stuff goes here
$(function(){
  PNC.ui.initAjaxSettings();
	$("#news_updates li").bigClickNYC();
	$("#initiatives_list .plus_button_link").hoverIntent(PNC.configs.initiativesListHoverConfig);
	$('#slideshow_images').cycle({
				//fx: 'scrollHorz',// choose your transition type, ex: fade, scrollUp, shuffle, etc...
				//speed:    1800, 
				//timeout:  8000,
				fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
				speed: 3000,
				timeout: 5000,
				prev:     '#prev', 
		    next:   '#next',
				after: function(currSlideElement, nextSlideElement, options, forwardFlag){
					$("#curr_index").text(options.currSlide + 1);
				}
			});
	$("input[type='text']").defaultValueActsAsHint();
	$(".zebra tr:odd, .zebra > li:odd").addClass("odd");
	$(".accordion").accordion({
		active: false,
		header: "a.accordion_handle",
		collapsible: true,
		alwaysOpen: false
	});
	
	$(".li_accordion>li>span").click(function(e) {
			if($(e.target).is("a") && !($(e.target).is("a[rel='toggle_handle']")))
				return true
			$(this).next().animate({height: "toggle"});
			$(this).toggleClass("expanded");
			return false;
		}).next().hide();
	
	$("#initiatives_list li, #initiatives_filterable_list li").live("mouseenter", function(e){
	  PNC.ui.imageFader.fadeToColor(e.target);
	});
	$("#initiatives_list li, #initiatives_filterable_list li").live("mouseleave", function(e){
	  PNC.ui.imageFader.fadeToBlackAndWhite(e.target);
	});
	
	$(".image_fade_container").live("fadecolor", function(e){
		PNC.ui.imageFader.fadeToColor(e.target);
	});
	
	$(".image_fade_container").live("fadebw", function(e){
		PNC.ui.imageFader.fadeToBlackAndWhite(e.target);
	});
	
	
	
	$("#slideshow_feature_visual").mouseenter(function(e){
		$("#slideshow_controls").fadeIn();
	});
	
	$("#slideshow_feature_visual").mouseleave(function(e){
		$("#slideshow_controls").fadeOut();
	});
	
	$("#newsletter_signup_form").submit(function(e){
	  e.preventDefault();
		$(this).find("#donate_btn").attr({"disabled": "disabled"}).css({"opacity": .5});
	  $(this).ajaxSubmit({
	    dataType: "json",
	    success: function(response){
	      if(response.success)
	        PNC.ui.popup(PNC.configs.newsletterSubscribeConfirmation.template(response));
	    }
	  });
	});
	
  $(".ajax_filter").ajaxFilter();
	
	$(".map_link").live("click", function(e){
	  e.preventDefault();
	  $("#map").dialog({
  	  modal: true,
  	  autoOpen: false,
  	  width: 600,
  	  height: 400,
  	  open: function() {
  	    $.getJSON($(e.target).attr("href"), function(response){
  	      var map = new PNC.ui.Map(response.initiative.address);
  	    })
  	  },
  	  close: function() {
  	    $("#map").dialog("destroy");
  	  }
      
  	});
	  $("#map").dialog("open");
	});
});


var isEmpty = function(obj) {
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) return false;
    }
    return true;
};

String.prototype.template = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );

};

/*
2 parseUri 1.2.1
3 (c) 2007 Steven Levithan <stevenlevithan.com>
4 MIT License
5*/

function parseUri (str) {
 var o = parseUri.options,
 m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
 uri = {},
 i = 14;

 while (i--) uri[o.key[i]] = m[i] || "";

 uri[o.q.name] = {};
 uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
 if ($1) uri[o.q.name][$1] = $2;
 });

 return uri;
};

parseUri.options = {
 strictMode: false,
 key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
 q: {
 name: "queryKey",
 parser: /(?:^|&)([^&=]*)=?([^&]*)/g
 },
 parser: {
 strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
 loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
 }
};



(function($){
  $.fn.ajaxFilter = function(collection){
    var collection = this;
    
    function buildQuery() {
      var data = {};
      data.areas = getChecked("areas");
      data.years = getChecked("years")
      data.fund_ranges = getChecked("amount")
      for (var prop in data) {
    		if (data[prop] == '') 
    			data[prop] = "all"
    	}
      return data;
    }
    
    function getChecked(name){
      return $(collection).filter("input[name=" + name + "]:checked").map(function(){
        return $(this).val();
      }).get().join(",");
    }
    
    function handleAjaxResponse(response) {
      $("#initiatives_filterable_list").replaceWith($(response).find("#initiatives_filterable_list"))
      $("#initiatives_container").fadeIn();
    }
    
    function do_request() {
      $("#initiatives_container").fadeOut();
      $.get("/our_initiatives", buildQuery(), function(response){
        handleAjaxResponse(response);
      });
    }
    
    $(document).bind("remove_initiative_filters", function(e){
      do_request();
    })
    
    return this.each(function() {
      $(this).click(function(e){
        if($(this).is(":checked"))
          $("#all_initiatives").attr({"checked" : false })
        do_request();
      })
    });
  }
})(jQuery);


//jquery plugins below here
(function($){
	//this just applies a hover class on hoer to any element with class ie_hover
	//because ie doesn't like css like li:hover
	$(function(){
		$(".ie_hover").hover(function(e){
			$(this).addClass("hover");
		},
		function(e){
			$(this).removeClass("hover");
		})
	})
	
})(jQuery);

(function($){

 $.fn.bigClickNYC = function(selector) {
 	var selector = selector || "a";
 	return this.each(function(){
 		$(this).click(function(e){
 			e.preventDefault();
 			if($(this).is(selector))
 				$(window).attr("location", $(this).attr("href"));
 			else if($(this).find(selector).length > 0)
 				$(window).attr("location", $(this).find(selector).attr("href"));
 			else{
 				//do nothing NYC!
 			}
 		});

		$(this).mouseover(function(e){
			$(this).css({"cursor": "pointer"})
		})
 	});
 }

})(jQuery);


(function($){
	$.fn.defaultValueActsAsHint = function(){
	 return this.each(function() {
			$(this).focus(function(){
			if(this._default != this.value) return;
			this.value = "";
		}).removeClass('hint').blur(function(){
			if(this.value != '') return;
			this.value = this._default;
			}).addClass('hint').get(0)._default = $(this).val();
		})
	};
})(jQuery);

/**
 * @author Alexander Farkas
 * @ version 1.05
 */
(function($){
	
	function getFnIndex(args){
		var ret = 2;
		$.each(args, function(i, data){
			
			if($.isFunction(data)){
				ret = i;
				return false;
			}
		});
		return ret;
	}
	
	
(function(){
	
	var contains = document.compareDocumentPosition ?  function(a, b){
		return a.compareDocumentPosition(b) & 16;
	} : function(a, b){
		return a !== b && (a.contains ? a.contains(b) : true);
	},
	oldLive = $.fn.live,
	oldDie = $.fn.die;
	
	function createEnterLeaveFn(fn, type){
		return jQuery.event.proxy(fn, function(e) {
			if( this !== e.relatedTarget && e.relatedTarget && !contains(this, e.relatedTarget) ){
				e.type = type;
				fn.apply(this, arguments);
			}
		});
	}
	
	var enterLeaveTypes = {
		mouseenter: 'mouseover',
		mouseleave: 'mouseout'
	};
	
	$.fn.live = function(types){
		var that 	= this,
			args 	= arguments,
			fnIndex 	= getFnIndex(args),
			fn 		= args[fnIndex];
		
		$.each(types.split(' '), function(i, type){
			var proxy = fn;
			
			if(enterLeaveTypes[type]){
				proxy = createEnterLeaveFn(proxy, type);
				type = enterLeaveTypes[type];
			}
			args[0] = type;
			args[fnIndex] = proxy;
			oldLive.apply(that, args);
		});
		return this;
	};
	
	$.fn.die = function(type, fn){
		if(/mouseenter|mouseleave/.test(type)){
			if(type == 'mouseenter'){
				type = type.replace(/mouseenter/g, 'mouseover');
			} 
			if(type == 'mouseleave') {
				type = type.replace(/mouseleave/g, 'mouseout');
			}
		}
		oldDie.call(this, type, fn);
		return this;
	};
	
	
	function createBubbleFn(fn, selector, context){
		return jQuery.event.proxy(fn, function(e) {
			var parent = this.parentNode,
				stop 	= (enterLeaveTypes[e.type]) ? e.relatedTarget : undefined;
			fn.apply(this, arguments);
			while(parent && parent !== context && parent !== e.relatedTarget){
				if($.multiFilter( selector, [parent] )[0]){
					fn.apply(parent, arguments);
				}
				parent = parent.parentNode;
			}
		});
	}
	
	$.fn.bubbleLive = function(){
		var args 	= arguments,
			fnIndex = getFnIndex(args);
		
		args[fnIndex] = createBubbleFn(args[fnIndex], this.selector, this.context);
		$.fn.live.apply(this, args);
	};
	
	$.fn.liveHover = function(enter, out){
		return this.live('mouseenter', enter)
					.live('mouseleave', out);
	};
})();



(function(){
	
	$.support.bubblingChange = !($.browser.msie || $.browser.safari);
	
	if(!$.support.bubblingChange){
	
	var oldLive = $.fn.live,
		oldDie = $.fn.die;
	
	function detectChange(fn){
		return $.event.proxy(fn, function(e){
			var jElm = $(e.target);
			if ((e.type !== 'keydown' || e.keyCode === 13) && jElm.is('input, textarea, select')) {
				
				var oldData 			= jElm.data('changeVal'), 
					isRadioCheckbox 	= jElm.is(':checkbox, :radio'),
					nowData;
				if(isRadioCheckbox && jElm.is(':enabled') && e.type === 'click'){
					nowData = jElm.is(':checked');
					if((e.target.type !== 'radio' || nowData === true) && e.type !== 'change' && oldData !== nowData){
						e.type = 'change';
						jElm.trigger(e);
					}
				} else if (!isRadioCheckbox) {
					nowData = jElm.val();
					if(oldData !== undefined && oldData !== nowData){
						e.type = 'change';
						jElm.trigger(e);
					}
				}
				if(nowData !== undefined){
					jElm.data('changeVal', nowData);
				}
			}
		});
	}
	
	function createChangeProxy(fn){
		return $.event.proxy(fn, function(e){
			if(e.type === 'change'){
				var jElm 	= $(e.target),
					nowData = (jElm.is(':checkbox, :radio')) ? jElm.is(':checked') : jElm.val();
				if(nowData === jElm.data('changeVal')){
					return false;
				}
				jElm.data('changeVal', nowData);
			}
			fn.apply(this, arguments);
		});
	}
	
	$.fn.live = function(type, fn){
		var that 	= this,
			args 	= arguments,
			fnIndex	= getFnIndex(args),
			proxy 	= args[fnIndex];
			
		if(type.indexOf('change') != -1){
			$(this.context)
				.bind('click focusin focusout keydown', detectChange(proxy));
			proxy = createChangeProxy(proxy);
		}
		args[fnIndex] = proxy;
		oldLive.apply(that, args);
		return this;
	};
	$.fn.die = function(type, fn){
		if(type.indexOf('change') != -1){
			$(this.context)
				.unbind('click focusin focusout keydown', fn);
		}
		oldDie.apply(this, arguments);
		return this;
	};
	
	}
})();

/**
 * Copyright (c) 2007 Jörn Zaefferer
 */


(function(){
	$.support.focusInOut = !!($.browser.msie);
	if (!$.support.focusInOut) {
		$.each({
			focus: 'focusin',
			blur: 'focusout'
		}, function(original, fix){
			$.event.special[fix] = {
				setup: function(){
					if (!this.addEventListener) {
						return false;
					}
					this.addEventListener(original, $.event.special[fix].handler, true);
				},
				teardown: function(){
					if (!this.removeEventListener) {
						return false;
					}
					this.removeEventListener(original, $.event.special[fix].handler, true);
				},
				handler: function(e){
					arguments[0] = $.event.fix(e);
					arguments[0].type = fix;
					return $.event.handle.apply(this, arguments);
				}
			};
		});
	}
	//IE has some troubble with focusout with select and keyboard navigation
	var activeFocus = null, block;
	
	$(document)
		.bind('focusin', function(e){
			var target = e.realTarget || e.target;
			if (activeFocus && activeFocus !== target) {
				e.type = 'focusout';
				$(activeFocus).trigger(e);
				e.type = 'focusin';
				e.target = target;
			}
			activeFocus = target;
		})
		.bind('focusout', function(e){
			activeFocus = null;
		});
		
})();
})(jQuery);

