$(document).ready(function (){
	$("#recent_news").NewsScroller();
	
	$("#latest_white_papers").WhitePaperScroller();
	
	$(".page_sidebar ul").stickyPanel({
		afterDetachCSSClass: "stickybox"
	});
	
	if($("#find_rec_form").length)
		$("#find_rec_form").prepend($("<input type=\"hidden\" value=\"1\" name=\"data[rec_finder][javascript]\" />"));
	
	if($("#map_container").length && map_options)
	 	$("#map_container").RecFinderMap(map_options);
	
	$("#lead_form").LeadForm();
	
	$("#lead_form_container").hide();
	$("a.show_lead_form").click(function(event){
		event.preventDefault();
		
		var id = $(this).attr("href");
		var form = $(id);
		
		if(form.is(":hidden")){
			form.slideDown("fast", function (){
				$("#main_lead_form_link").text($("#main_lead_form_link").text().replace(/Show/,"Hide"));
			});
		}
		else{
			form.slideUp("fast", function(){
				$("#main_lead_form_link").text($("#main_lead_form_link").text().replace(/Hide/,"Show"));
			});
		}
	});
	
	$( "#documents_table" ).tablesorter();
	$("#documents_table").bind("sortEnd",function() {
		var $this = $(this);
		$( "tbody tr:even", $this ).removeClass( "even" ).addClass( "odd" );
		$( "tbody tr:odd", $this ).removeClass( "odd" ).addClass( "even" );
		$( "#last_row" ).removeClass( "last_row" );
		$( "tbody tr:last", $this ).attr( "id", "last_row" );
	});
	
	$documentSearch = $( "#document_search_input" );
	if( $documentSearch.length ) {
		$tableRows = $( "#documents_table tbody tr" );
		
		$documentSearch.keyup(function (e) {
			var $this = $( this ),
					currentValue = $this.attr("value"),
					regEx = new RegExp( currentValue.trim(), "/i");
					
			$tableRows.each( function(i, el) {
				var $row = $(el);
				if( currentValue !== "" ) {
					if( $(el).text().search( regEx ) === -1 ) {
						$row.fadeOut("fast");
					} else {
						$row.fadeIn("fast");
					}
				} else {
					$row.fadeIn("fast");
				}
			})
		});
	}
	
	$ehr_eligibility_widget = $( "#ehr_eligibility_widget_wrapper" );
	if( $ehr_eligibility_widget.length == 1 ) {
		var eligibiltyOpenMessage 	= "Click to Open the Eligibility Tool.",
				eligibiltyCloseMessage	= "Click to Close the Eligibility Tool.",
				$eligibiltyTriggerWrapper = $("<p />")
				$eligibiltyTriggerLink 	= $( "<a href=\"#ehr_eligibility_widget_wrapper\" />" );
				
		$eligibiltyTriggerLink.click(function (e) {
			e.preventDefault();
			if( $ehr_eligibility_widget.is(":hidden") ) {
				$ehr_eligibility_widget.slideDown( "fast", function(){
					$eligibiltyTriggerLink.text( eligibiltyCloseMessage )
				});
			} else {
				$ehr_eligibility_widget.slideUp( "fast", function(){
					$eligibiltyTriggerLink.text( eligibiltyOpenMessage );
				});
			}
		});
		
		$eligibiltyTriggerLink.html( eligibiltyOpenMessage );
		$eligibiltyTriggerWrapper.append( $eligibiltyTriggerLink );
		$ehr_eligibility_widget.before( $eligibiltyTriggerWrapper );
		$ehr_eligibility_widget.hide();
	}
	
	$blumenthal_announcement = $( "#blumenthal_announcement" );
	if( $blumenthal_announcement.length == 1 ) {
		var blumenthalOpenMessage 	= "Click to view Dr. Blumenthal's Announcement.",
				blumenthalCloseMessage	= "Click to close Dr. Blumenthal's Announcement",
				$blumenthalTriggerWrapper = $("<p />")
				$blumenthalTriggerLink 	= $( "<a href=\"#blumenthal_announcement\" />" );
				
		$blumenthalTriggerLink.click(function (e) {
			e.preventDefault();
			if( $blumenthal_announcement.is(":hidden") ) {
				$blumenthal_announcement.slideDown( "fast", function(){
					$blumenthalTriggerLink.text( blumenthalCloseMessage )
				});
			} else {
				$blumenthal_announcement.slideUp( "fast", function(){
					$blumenthalTriggerLink.text( blumenthalOpenMessage );
				});
			}
		});
		
		$blumenthalTriggerLink.html( blumenthalOpenMessage );
		$blumenthalTriggerWrapper.append( $blumenthalTriggerLink );
		$blumenthal_announcement.before( $blumenthalTriggerWrapper );
		$blumenthal_announcement.hide();
	}
	$("#index_rec_finder").RecFinder();
});

(function($){
	$.fn.RecFinder = function(){
		return $(this).each(function(){
			$this = $(this);
			$this.addClass("with_js");
			$main_input = $("#rec_finderZipCode",$this);
			
			$intro_message = "Click here to find your REC";
			
			$instructions = $("<div id=\"rec_instructions_js\"><div id=\"rec_instructions_pointer\"></div></div>");
			$instructions.append($("#index_rec_finder_instructions",$this).html());
			$instructions.hide();
			$this.after($instructions);
			
			$instructions.css({
				"top"		: $this.position().top + $this.outerHeight(true) + 10 + "px",
				"width"	: ($main_input.width() - 4) + "px",
				"left"	: $main_input.position().left + "px"});
			
			$main_input.focus(function(e){
				$this = $(this);
				$this.css("color", "#000");
				
				$instructions.fadeIn("fast");
				
				if(jQuery.trim($this.val()) == $intro_message)
					$this.val("");
			});
			
			$main_input.blur(function(e){
				$this = $(this);
				
				$instructions.fadeOut("fast");
				
				if(jQuery.trim($this.val()) == "")
					add_intro_message();
			})
			
			add_intro_message = function(){
				$main_input.val($intro_message);
				$main_input.css("color","#917a55");
			}
			
			add_intro_message();
		});
	}
})(jQuery);

(function($){
	$.fn.LeadForm = function(){
		return $(this).each(function(){
			$this = $(this);
			
			$this.submit(function(event){
				function add_error_message(el, message){
					fields_with_errors.push(el);
					var id = $(el).attr("id");
					var label = $("label[for=" + id + "]").text().replace("*","");
					var error_message = label + " " + message;
					var container = $(el).parents(".lead_form_field");
					container.addClass("error");
					if(!$(".error-message", container).length){
						container.append($("<div class=\"error-message\">Your " + error_message.toLowerCase() + "</div>"));
					} else {
						$(".error-message", container).text("Your " + error_message.toLowerCase());
					}
				}
				
				function remove_error_messages(el){
					var container = $(el).parents(".lead_form_field");
					container.removeClass("error");
					$(".error-message", container).detach();
				}
				
				var fields_with_errors = new Array()
				
				$(".required", $this).each(function(i, el){
					if(!$(el).val()){
						add_error_message(el, "is required.");
					}
					else {
						remove_error_messages(el);
					}
				});
				
				$(".email", $this).each(function(i, el){
					var value = $(el).val();
					if(value){
						if(!value.match(/^[a-zA-Z0-9._%+-]+@(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,4}$/)){
							add_error_message(el, "must be a valid email address.");
						}
						else{
							remove_error_messages(el);
						}
					}
				});
				
				$(".zip_code", $this).each(function(i, el){
					var value = $(el).val();
					if(value){
						if(!value.match(/^\d+$/)){
							add_error_message(el, "must be all numbers.");
						}
						else if(value.length != 5){
							add_error_message(el, "must be 5 digits long.")							
						}
						else{
							remove_error_messages(el);
						}
					}
				});
				
				$(".phone", $this).each(function(i, el){
					var value = $(el).val();
					
					if(value){
						if(!value.match(/^\(\d{3}\)\s*[0-9]{3}\-\d{4}$/)){
							add_error_message(el, "must be in the proper format.");
						}
						else {
							remove_error_messages(el);
						}
					}
					else{
						remove_error_messages(el);
					}
				});
				
				if(fields_with_errors.length){
					event.preventDefault();
					if(!$("#form_error_message", $this).length){
						$this.prepend("<div id=\"form_error_message\" class=\"error-message\">There were one or more errors in the form.  Please correct them and try again.</div>");
					}
				}
			});
		})
	}
})(jQuery);

(function($){
	$.fn.RecFinderMap = function(options){
		var recs_kml_files = {
			tech: 							"WestTexasREC",
			dfw: 								"NorthTexasRegionalHITExtensionCenterConsortium",
			uthsc: 							"GulfCoastHITECHExtensionCenter",
			centreast: 					"CentrEastRegionalExtensionCenter",
			alaska: 						"AeHN2",
			alabama: 						"ALREC",
			arizona: 						"AHeC",
			arkansas: 					"HITArkansas",
			colorado: 					"corec",
			connecticut: 				"eHealthConnecticut",
			delaware: 					"drec",
			georgia: 						"gahitrec",
			hawaii: 						"HawaiiHealthInformationExchange",
			idaho: 							"WIREC",
			ihtec: 							"IHITEC",
			iowa: 							"IFMC",
			KFMC: 	 						"KFMC",
			kentucky:						"KentuckyREC",
			tristate: 					"TriState",
			maine: 							"HealthInfoNet",
			maryland: 					"CRISP",
			massachusetts: 			"MeHI",
			michigan: 					"MCEITA",
			minnesota_ndakota: 	"REACH",
			missouri: 					"TheCuratorsUniversityMissouri",
			montana_wyoming: 		"MountainPacificQualityHealthFoundation",
			nebraska: 					"WideRiverTechnologyExtensionCenter",
			jersey: 						"NewJerseyInstituteTechnology",
			new_mexico: 				"LCFResearch",
			south_carolina: 		"CITIA",
			oklahoma: 					"OklahomaFoundationMedicalQuality",
			oregon: 						"OCHIN",
			puerto_rico: 				"PonceSchoolMedicine",
			rhode_island: 			"RhodeIslandQualityInstitute",
			south_carolina: 		"SouthCarolinaResearchFoundation",
			south_dakota: 			"HealthPoint",
			tennessee: 					"Qsource",
			utah_nevada: 				"HealthInsight",
			vermont: 						"VermontInformationTechnologyLeaders",
			virginia: 					"VHQC",
			west_virginia: 			"WestVirginiaHealthImprovementInstitute",
			wisconsin: 					"WHITEC",
			mississippi: 				"EQHealthSolutions",
			louisiana: 					"LouisianaHealthCareQualityForum",
			hitecla: 						"HITECLA",
			calhipso: 					"CalHIPSO",
			nycreach: 					"NYCREACH",
			nyec: 							"NYeC",
			ucf: 								"UCFREC",
			health_choice:      "HealthChoiceNetworkofFlorida",
			illinois: 					"IL-HITREC",
			wqip: 							"WQIP",
			eqip: 							"EQIP", 
			ohio: 							"OHIP",
			chca:								"CommunityHealthCentersAlliance",
			paperfree: 					"PaperFreeFlorida",
			orange: 						"CalOptima",
			new_hampshire:  		"RECNH",
			chitrec: 						"chitrec", 
			dc: 								"eHealthDC"
		};
		
		var settings = jQuery.extend({
			user_latitude: null,
			user_longitude: null,
			zoom: 6,
			center_latitude: 31.184609,
			center_longitude: -99.84375,
			init_roadmap_id: "ROADMAP",
			user_input: null,
			recs_to_display: {tech:1, dfw:1, uthsc:1, centreast:1}
		}, options);
			
		return $(this).each(function(options){
			if(google.maps){
				var el = {
					self: this,
					canvas: $("<div id=\"map_canvas\"></div>")
				}
				$(el.self).empty();
				$(el.self).append(el.canvas);
				
				var latlng = new google.maps.LatLng(settings.center_latitude, settings.center_longitude);
				
				var myOptions = {
					zoom: settings.zoom,
					center: latlng,
					mapTypeId: google.maps.MapTypeId[settings.init_roadmap_id],
					scrollwheel: false
				};
				
				var my_map = new google.maps.Map(el.canvas[0], myOptions);
				
				for(rec in settings.recs_to_display){
					new google.maps.KmlLayer("http://dev.centreastrec.org/files/kml/" + recs_kml_files[rec] + ".kml", {map: my_map, preserveViewport: true});
				}
				
				if(settings.user_latitude && settings.user_longitude){
					var location_info_window = new google.maps.InfoWindow({
						content: "<div style=\"font-weight: bold; font-size: medium; margin-bottom: 0em\">You are here</div><p>" + settings.user_input + "</p>."
					});
					
					$("#settings_user_input").text(settings.user_input);
					
					var user_location = new google.maps.LatLng(settings.user_latitude, settings.user_longitude);
					
					var user_location_marker = new google.maps.Marker({
					 	position: user_location,
						map: my_map,
					 	title: settings.user_input
					});
					
					location_info_window.open(my_map, user_location_marker);
				}
			}
		});
	}
})(jQuery);

(function($){
	$.fn.NewsScroller = function(){
		return $(this).each(function(){
			var el = {
				self: this,
				articles: $("ul", this)
			};
			var data = {
				current_art: 0,
				art_size: $("li",el.articles).length
			}
			
			if(el.articles.length == 0)
				$(el.self.hide());
			else
				$(el.self).addClass("with_js");
			
			if(data.art_size > 1){
				$(el.articles).hide();
				fade_in();
			}
			
			function fade_in(){
				$(el.articles).fadeIn(1000,function(){ setTimeout(fade_out, 4000);});
			}
			
			function fade_out(){
				$(el.articles).fadeOut(1000,function(){
					data.current_art++;
					if(data.current_art == data.art_size) data.current_art = 0;
					el.articles.css({"top": ($(el.self).innerHeight() * data.current_art * -1) + (1 * data.current_art) + "px"});
					fade_in();
				});
			}
		});
	}
}(jQuery));

(function ($) {
	$.fn.WhitePaperScroller = function() {
		return $(this).each( function () {
			var $this      			= $(this),
					$white_papers 	= $(".white_paper", $this),
					$white_paper_list = $(".lastest_white_paper_list"),
					$wp_navbar_container = $("<div id=\"wp_navbar_container\" />"),
					$links = [],
					current_paper 	= 0,
					ourTimeout = setTimeout( move, 3000 ),
					hoverOn = false;
					
			clearTimeout( ourTimeout );
						
			if( $white_papers.length === 0 ) {
				$this.hide();
			} else {
				$this.attr( "id", "latest_white_papers_js" );
			}
			
			if( $white_papers.length > 1 ) {				
				$white_papers.css({
					width: $white_papers.width() + "px"
				});
				
				$white_paper_list.append($white_papers.first().clone());
					
				$white_paper_list.css({
					width: ($this.innerWidth() * ($white_papers.length + 1)) + "px"
				});
				
				$white_papers.each( function ( i, el ) {
					$links[i] = $("<a href=\"#" + i + "\" />");
					$wp_navbar_container.append( $links[i] );
					
					$links[i].click( function (e){
						e.preventDefault();
						var number = parseInt($(this).attr("href").replace("#", ""));
						current_paper = number - 1
						clearTimeout( ourTimeout );
						move();
						return false;
					});
					
					$links[i].hover(function (e) {
							hoverOn = true;
							clearTimeout(ourTimeout);
						},
						function (e) {
							hoverOn = false;
							set_move();
					});
				});
				
				$this.append( $wp_navbar_container );

				var margin = parseInt($links[1].css('margin-left').replace("px", ""));
				$wp_navbar_container.css({
					width: (($links[0].width() + margin) * $links.length) + "px"
				});
				
				$links[0].addClass( "current_paper" );
				
				$white_paper_list.hover(function (e) {
						hoverOn = true;
						clearTimeout(ourTimeout);
					},
					function (e) {
						hoverOn = false;
						set_move();
				});
				
				set_move();
			}
			
			function set_move () {
				clearTimeout( ourTimeout );
				if( !hoverOn ) {
					ourTimeout = setTimeout( move, 4000 );
				}
			}
			
			function move () {
				log("move");
				current_paper = current_paper + 1;
				
				$(".current_paper").removeClass( "current_paper" );
				if( current_paper === $white_papers.length ) {
					$links[0].addClass( "current_paper" );
				} else {
					$links[current_paper].addClass( "current_paper" );
				}
				
				$white_paper_list.animate({
					left: ( $this.width() * current_paper * -1) + "px"
				}, "slow", "swing", function () {
					if( current_paper === $white_papers.length ) {
						current_paper = 0;
						$white_paper_list.css({
							left: "0px"
						});
					}
					
					set_move();
				});
			}
			
		});
	}
}(jQuery));

jQuery.fn.log = function(){
	if (window && window.console && window.console.log){
		if(arguments.length)
	    	for(var i=0, len = arguments.length; i < len; i++)
	      		console.log(arguments[i]);
		else
			console.log(this[0]);
	}
}

function log(message){
	jQuery.fn.log(message);
}

/*
*   jQuery.stickyPanel
*   ----------------------
*   version: 1.0.1
*   date: 1/17/11
*
*   Copyright (c) 2011 Donny Velazquez
*   http://donnyvblog.blogspot.com/
*   http://code.google.com/p/sticky-panel/
*   
*   Licensed under the Apache License 2.0
*
*/
(function ($) {

    $.fn.stickyPanel = function (options) {

        var options = $.extend({}, $.fn.stickyPanel.defaults, options);

        return this.each(function () {
            $(window).bind("scroll.stickyPanel", { selected: $(this), options: options }, Scroll);
        });

    };

    function Scroll(event) {
        var node = event.data.selected;
        var o = event.data.options;

        // when top of window reaches the top of the panel detach
        if ($(document).scrollTop() > (node.offset().top)) {

            // topPadding
            var top = 0;
            if (o.topPadding != "undefined") {
                top = top + o.topPadding;
            }

            // save panels top
            node.data("PanelsTop", node.offset().top - top);

            // afterDetachCSSClass
            if (o.afterDetachCSSClass != "") {
                node.addClass(o.afterDetachCSSClass);
            }

            // savePanelSpace
            if (o.savePanelSpace == true) {
                var width = node.outerWidth(true);
                var height = node.outerHeight(true);
                var float = node.css("float");
                var randomNum = Math.ceil(Math.random() * 9999); /* Pick random number between 1 and 9999 */
                node.data("PanelSpaceID", "stickyPanelSpace" + randomNum);
                node.before("<div id='" + node.data("PanelSpaceID") + "' style='width:" + width + "px;height:" + height + "px;float:" + float + ";'></div>");
            }

            // detach panel
            node.css({
                "top": top,
                "position": "fixed"
            });

        }

        if ($(document).scrollTop() <= node.data("PanelsTop")) {

			if (o.savePanelSpace == true) {
				$("#" + node.data("PanelSpaceID")).remove();
			}
			
            // attach panel
            node.css({
                "top": "auto",
                "position": "static"
            });

            if (o.afterDetachCSSClass != "") {
                node.removeClass(o.afterDetachCSSClass);
            }
        }

    };

    $.fn.stickyPanel.defaults = {
        topPadding: 0,
        // Use this to set the top margin of the detached panel.

        afterDetachCSSClass: "",
        // This class is applied when the panel detaches.

        savePanelSpace: false
        // When set to true the space where the panel was is kept open.
    };

})(jQuery);

