/**
 * PH global namespace
 */ 
var PH = {};

PH.slideshow = {
	 /**
     * Initializes the slidehow module
     */
	init: function() {	
		var config = {
			container:"#slideshow",
			slides:"div.slides"
		};

		var slideshow = $(config.container);
		var slides = slideshow.find(config.slides);
		var prev = slideshow.find('a.prev');
		var next = slideshow.find('a.next');
			
		slides.cycle({ 
			fx:     'fade', 
			speed:   600,
			timeout: PH.SLIDESHOW_SPEED,
			pause:   1,
			next:   next,
			prev:   prev,
			pager: slideshow.find('.pager')
		});	
		
		//show first slide if there is only one
		if(slides.length == 1) {
			slides.find("div").show();
		}
	}
}

PH.descreteAudienceDropdown = {
 	/**
     * Initializes the descrete audience dropdown
     */
	init: function() {
		var input = $(".descrete-audience-form input");
			
		input.each(function() {
			$(this).click(function(e) {
				e.preventDefault();
				var selected = $(this).parent().find("select option:selected");
				window.location = selected.val();
			});
		});
	}
}

/**
* Insurance Information
*/
PH.insuranceInformation = {
 	/**
     * Initializes the insurance information module
     */
	init: function() {
		var select = $("#insurance-information select");
		
		//show first item on page load
		$(".insurance-state").eq(0).show();
		select.attr('selectedIndex', 0);
		
		select.change(function(e) {
			e.preventDefault();
			var selected = $(this).find("option:selected");
			$(".insurance-state").hide();
			$("#insurance-state-" + selected.val()).fadeIn();
		});			
	}
}

/**
* Get Help Button
*/
PH.getHelp = {
	init: function() {
		$("#get-help-popup").hover(function() {
			$("#get-help-popup ul").show();
		}, 
		function() {
			$("#get-help-popup ul").hide();
		});		
	}
}

/**
* Info Popup
*/
PH.infoPopup = {
	init: function() {
		
		$(document).click(function(e) {
			if($(e.target).attr('class') != "open-info-popup") {
				$(".info-popup").removeClass("active");
			}	
		});
		
		$(".open-info-popup").click(function(e) {
			e.preventDefault();
			$(this).parent().find(".info-popup").addClass("active");
		});
		
		$(".open-info-popup").hover(function(e) {
			e.preventDefault();
			$(this).parent().find(".info-popup").addClass("active");
		});
		
		$(".close-info-popup").click(function(e) {
			e.preventDefault();
			$(this).parent().parent().find(".info-popup").removeClass("active");
		});
	},
	openPopup: function(obj) {
		$(obj).parent().find(".info-popup").addClass("active");
	}
}

/**
* Clear Input field on Focus
*/
PH.clearInput = {
	init: function() {
		$(".zip-input, .searchField, .comment-input").focus(function() {
			$(this).val('');
		});
		
		var zipInput = $(".zip-input");
		
		if($("body.page-template-page-zip-search-php").length != 0) {
			zipInput.val("Enter Another Zip Code or City");
		} else {
			zipInput.val("Search State or Zip");
		}
	}
}

/**
* Add error message for regular search fields
*/
PH.searchErrors = {
	init: function() {
		$(".searchSubmit").click(function(e) {
			e.preventDefault();
			var form = $(this).parent();
			var sInput = $(form).find(".searchField");
			
			if ( $(sInput).val() == "" || $(sInput).val() == "Search" ) { 
				$(sInput).val("Please enter term.");
			} else {
				form.submit();
			}
			
		});
	}
}

/**
* Prevent Comment Submission in case of placeholder text
*/
PH.commentPrevention = {
	init: function() {
		$("#commentform").submit(function(e) {
			if ($("#author").val() == "Name" || $("#email").val() == "E-mail" || $("#comment").val() == "Comment") {
		        e.preventDefault();
		    }
	    });
	}
}

/**
* Social Module. Get Facebook Feed from Facebook Page
*/
PH.facebook = {
	init: function() {
		//95763090335 //196568009482
		var url = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20feed%20where%20url%3D'http%3A%2F%2Fwww.facebook.com%2Ffeeds%2Fpage.php%3Fformat%3Datom10%26id%3D95763090335'&format=json&diagnostics=true&callback=PH.facebook.showData";
        $.getScript(url);
	},
	showData: function(data) {

		if(PH_FB_FilterCode == undefined) {
			var PH_FB_FilterCode = "";
		}
		
		if(data.query.results != null) {
			var entries = data.query.results.entry;
			var author = "";
			var title = "";
			var published = "";
			var time = "";
			var entry = "";
			var i = 0;
			
			$.each(entries, function(index, entry) {
				title = entry.title;
				if( title.indexOf(PH_FB_FilterCode) != -1 ) {
					entry = entries[index];
					i = index;
					return false;
				} 
					
			});
			
			entry = entries[i];
			
			published = entry.published;
			
			if(i != 0) {	
				//remove filterCode
				title = title.replace(PH_FB_FilterCode, "");
				
				//remove whitespace
				title = title.replace(/^\s*/, '').replace(/\s*$/, '');
			}
			 
			var date = new Date(published);
			time = published.split("T")[1].split("+")[0];
	
			var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November",
							"December");
	
			published = m_names[date.getMonth()] + " " + date.getDate();
			author = entry.author.name;
			
			$(".facebook .module-content").html('<p><a class="link-blue" href="http://www.facebook.com/PhoenixHouse" target="_blank">' + author + '</a>: "' + title + '"<span>Published on ' + published + ' at ' + time + '</span></p>');
		}
	}
}

/**
* IE6 Fix for Persistent Footer Bar
*/
PH.helpBar = {
	init: function() {
		var bar = $("#global-bar-container");

		$(window).scroll(function() {
  			$(bar).css({position: "absolute",top:($(window).scrollTop()+$(window).height()-$(bar).height())+"px"})	
  		});
	}
	
}


/**
* Google Api Zip Search
*/
PH.zipSearch = {
	googleJSisLoaded:false,
	markers:[],
	init: function() {
		this.handler();
		this.loadGoogleJS();
	},
	handler: function() {
		/*
		* Add error message when no search term is entered
		*/
		$(".zip-input").keypress(function(e){
			var form = $(this).parent();
			var zipInput = $(form).find(".zip-input");
			
      		if(e.which == 13){
       			PH.zipSearch.initSearch($(zipInput).val(), form);
       		}
      	});

		$(".btn-search-location").live("click", function(e) {
			
			e.preventDefault();
			var form = $(this).parent();
			var zipInput = $(form).find(".zip-input");
			
			if ( $(zipInput).val() == "" || 
				 $(zipInput).val() == "Search State or Zip" || 
				 $(zipInput).val() == "Enter Another Zip Code or City") {
		         $(zipInput).val('Please enter search term.');
		    } else {
		    	PH.zipSearch.initSearch($(zipInput).val(), form);
		    }
	    });
	    
	    $("#did-you-mean-result a").click(function(e) {
	    	e.preventDefault();
	    	
	    	$("#map-sidefoot .location-search").find(".zip-input").val($(this).text());	
	    	$("#map-sidefoot .btn-search-location").trigger("click");
	    	
	    });
	},
	/*
	* Load Google Maps API
	*/
	loadGoogleJS: function() {	
		var script = document.createElement("script");
    	script.type = "text/javascript";
    	script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=PH.zipSearch.initGoogleMap";
    	document.body.appendChild(script);	
	},
	/*
	* Do a google map api search
	*/
	initSearch: function(location, form) {
		var zipInput = $(form).find(".zip-input");
		zipInput.val(location);
		this.searchLocations(form);
	},
	searchLocations: function(form){
		var address = $(form).find(".addyInput").val();
		var geocoder = new google.maps.Geocoder();
		
		geocoder.geocode({address: address}, function(results, status) {
		
			if (status == google.maps.GeocoderStatus.OK) {
				tester = results;	
				 //found more than 1 result
				 if (results[1]) {
				 	var result = "";
				
				for(var i=0;i<results.length;i++) {
					result += results[i].formatted_address + ";";
				}
				
				$('#multiple-results').val(result);
			 } 
			 
			 center = results[0].geometry.location;
			 $("#lat").val(center.lat());
			 $("#long").val(center.lng());
			 $("#address").val(address);
			 
			 if (! results[1]) {
			   $('#multiple-results').val(results[0].formatted_address);
			 }
			
			 $("#hidden-form").submit();
			 
			} else {
				$("#zip-results").empty().append('<div id="no-results-zip"></div>');
			 	$("#zip-container .module-header h2.mod-title").html('There is no location near: '+address);
			}
			
		});
	},
	/*
	* Init Map
	*/
	initGoogleMap: function() {
		
		if(typeof lat != 'undefined' && typeof long != 'undefined' && typeof results != 'undefined') {
			
			var zoom = 8;
			if ( ! lat ) {
				lat = 39.50;
				long = -98.35;
				zoom = 3;
			}
			
			var map_center = new google.maps.LatLng(lat,long);
		    var map_options = {
		      zoom: zoom,
		      center: map_center,
		      mapTypeId: google.maps.MapTypeId.ROADMAP
		    }
		    
	    	var map = new google.maps.Map(document.getElementById("map_canvas"), map_options);		
			
			var bounds = new google.maps.LatLngBounds();
			var bounds_i = 0;
			$(results).each(function(){
				var LatLng = new google.maps.LatLng(this[0][0],this[0][1]);
				if (bounds_i < 10) {
					bounds.extend (LatLng);
					bounds_i++;
				}
				PH.zipSearch.createMarker( LatLng, this[1], this[2], this[3], map );
			});
			map.fitBounds (bounds);
		}	
	},
	/*
	* Google Maps API Markers
	*/
	createMarker: function(latlng, name, addressInfo, id, map) {		
		var addrURL =	encodeURIComponent(addressInfo.address) + "+" +
						encodeURIComponent(addressInfo.city + ", " + addressInfo.state) + "+" +
						encodeURIComponent(addressInfo.zip);
						
		var html = "<b>" + name + "</b> <br/>" + 
						addressInfo.address + "<br/>" +
						addressInfo.city + ", " + addressInfo.state + "<br/>" +
						addressInfo.zip + "<br/>"+
						'<a target="_blank" href="'+'http://maps.google.com/maps?saddr=&daddr='+addrURL+'">Get Directions</a>';
		var marker = new google.maps.Marker({
		map: map,
		position: latlng,
		title: name
		});
		
		var infoWindow = new google.maps.InfoWindow({});
		
		var markerClickFunc = function(e) {
			
			e.preventDefault();
			$(PH.zipSearch.markers).each(function(){
				this.infoWindow.close();
			})
			
			infoWindow.open(map, marker);
		};
		
		google.maps.event.addListener(marker, 'click', markerClickFunc);
		
		$('#result-'+id + " .link-map").click(markerClickFunc);
		
		infoWindow.setContent(html);
		PH.zipSearch.markers.push({marker:marker,infoWindow:infoWindow});
		
	}
}

/**
* Additional Services
*/
PH.additionalServices = {
	init: function() {
		// set equal heights for columns
		//$("#additional-services li").equalHeights(200,500);
		
		//remove empty p tags which are generated by tinymce
		$("#additional-services li").each(function() {
			
			if($(this).find("img").length != 0) {
				$(this).find("p").addClass("padding-90");
			}
			
			var pTag = $(this).find("p").eq(0);
			
			if(pTag.html() == "" || pTag.text() == "") {
				pTag.remove();
			}
		});		
	}
}

/* resize arrows and homepage hero box based on browser window */
PH.resize = {
	init: function() {
		
		$(window).resize(function() {
 			PH.resize.resize();
		});		
	},
	resize: function() {
		//resize arrows
		if($(window).width() < 1134) {
			var headerContentPosition = $(".header-content").position();
			$(".featured-box, .featured-box-inner").css({ "left":$(window).width()-270});
			$("#slideshow .navigation").css({ "width":$(window).width()-40, "left":"0", "position":"absolute","marginLeft":"20px", "marginRight":"20px"});
		} else {
			$("#slideshow .navigation").css({ "width":"1111", "left":"24px","marginLeft":"0", "marginRight":"0"});
			$(".featured-box, .featured-box-inner").css({ "right":"110px"});	
		} 
	}
}


$(document).ready(function() { 
	PH.descreteAudienceDropdown.init();
	PH.insuranceInformation.init();
	PH.getHelp.init();
	PH.infoPopup.init();
	PH.clearInput.init();
	PH.commentPrevention.init();
	PH.searchErrors.init();
	
	//init slideshow
	if($("#slideshow").length != 0) {
		PH.slideshow.init();
	}
	
	//init equal height for locations
	//if($(".location").length != 0) {
	//	$(".location").equalHeights(100,300);
	//}
	
	//additional services module
	if($("#additional-services").length != 0) {
		PH.additionalServices.init();
	}
	
	//social module facebook		
	if($("div.facebook").length != 0) {
		PH.facebook.init();
	}
	
	//ie6 workaround for sticky footer
	if($.browser.msie && $.browser.version.substring(0,1) === '6') {
		PH.helpBar.init();
	}
	
	//google zip search
	PH.zipSearch.init();
	
	PH.resize.init();
	PH.resize.resize();

}); 



















