//media scroller define custom event for youtube
function onYouTubePlayerReady(playerId) {
  	var ytplayer = document.getElementById(playerId);
	ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

//detected youtube event
function onytplayerStateChange(newState) {
	if (newState == 1) {
		$("#mediaScrollerBox").scrollable().stop();
		if ($(".navi", $("#mediaScrollerBox")).css('display') == 'block') {
			$(".overlayText", $("#mediaScrollerBox")).slideToggle();
			$(".navi,.browse", $("#mediaScrollerBox")).hide();
		}
	} else if (newState == 0 || newState == 2) {
		$("#mediaScrollerBox").scrollable().play();
		if ($(".navi", $("#mediaScrollerBox")).css('display') == 'none') {
			$(".overlayText", $("#mediaScrollerBox")).slideToggle();
			$(".navi,.browse", $("#mediaScrollerBox")).show();
		}
	}
}

//resize video iframe to fit content
function configVideoFrame() {
	var pm = $("#pageModule");
	
	$(".iframevideo", pm).each(function() {
		var cw = $(this).width();
		var ch = $(this).height();
		
		var i = $("iframe", $(this));
		var ratio = i.width() / cw;
		
		i.width(cw);
		i.height(parseInt(i.height()/ratio));
		
		var url = i.attr("src");
		if (url.search("\\?") >= 0) {
			i.attr("src",url+"&wmode=transparent")
		} else {
			i.attr("src",url+"?wmode=transparent")
		}
		
	})
}

$(document).ready(function() {
	
	//media scroller
	if ($("#mediaScrollerBox").length > 0) {
		$(window).load(function(){
			//media scroller
			
			$("#mediaScrollerBox").scrollable({
				circular: true,
				onBeforeSeek: function(event, si){
					$("#mediaScrollerBox").scrollable().stop();
					if ($(".navi", $("#mediaScrollerBox")).css('display') == 'block') {
						$(".navi", $("#mediaScrollerBox")).hide();
						$(".overlayText", $("#mediaScrollerBox")).slideToggle();
					}
				},
				onSeek: function(){
					$("#mediaScrollerBox").scrollable().play();
					if ($(".navi", $("#mediaScrollerBox")).css('display') == 'none') {
						$(".overlayText", $("#mediaScrollerBox")).slideToggle(function(){
							$(".navi", $("#mediaScrollerBox")).show();
						});
					}
				}
			}).autoscroll({
				interval: $(this).attr('delay'),
				autopause: false
			});
			
		});
		
		$("#hitest").click(function(){
			ytplayer = document.getElementById("myytplayer1")
			ytplayer.playVideo();
			
			return false;
		})
	}
	
	//dropdown menu
	if ($("#programs-dropdown").length > 0) {
		$("#programs-dropdown").hide();
		
		$("#drop-downed").mouseenter(function(){
			$("#programs-dropdown").show();
		}).mouseleave(function(){
			$("#programs-dropdown").hide();
		});
	}
	
	
	//find a location popup menu
	$("#findLocationMenu").click(function() {
		var theURL = $(this).attr('ajxURL');
		var theSelect = $("#findLocationSel");
		$(this).addClass('hover');
		
		if (typeof(theSelect.data('cityData')) == 'undefined') {
			$.ajax({
				type: "GET",
				url: theURL,
				dataType: "json",
				success: function(data){
					if ($.isArray(data) && data.length > 0) {		
						$.each(data, function(intIndex, intValue) {
							theSelect.append("<option value='"+intValue.ACT+"'>"+intValue.NAME+"</option>")
						});
						theSelect.data("cityData",data);
						//theSelect.val(0);
					}
				},
				error: function(h,s,e){
					alert( 'Error retrieving cities. Please try again.' );
				}
			});
		}
		
		theSelect.change(function() {
			window.location.href=$(this).attr('ajxURL')+$(this).val();
		});
		
		$("#mainContainer").hover(function() {
			$("#findLocationMenu").removeClass('hover');
		});
		
		return false;
		
	});
	
	
	//setup page modules
	if ( $("#pageModule").length > 0 ) {
		
		configVideoFrame();
		
	}
	
	
	
	//setup various about us pages
	if ( $("#staff-search-tabs").length > 0 ) {
		$("#staff-search-tabs").tabs();
	} else if ( $("#partner-search-tabs").length > 0 ) {
		$("#partner-search-tabs").tabs();
	} else if ( $("#gov-affairs-tabs").length > 0 ) {
		$("#gov-affairs-tabs").tabs();
	} else if ( $("#sg-tabs").length > 0) {
		$("#sg-tabs").tabs();
	} else if ( $("#job-accordion").length > 0 ) {
		$("#job-accordion").accordion({
			collapsible: true,
			active: false
		});
	}
	
	
	
	
	
	
	//setup city swap
	if ( $("#citySwap").length > 0 ) {
		
		$("#citySwap").change(function() {
			var theURL = $(this).attr('href');
			
			window.location.href=theURL + $(this).val();
			
		});
		
	}
	
	
	//contact bio
	if ( $("#staffingBox").length > 0) {
		$(".staffContactBioLnk", $("#staffList")).live('click', function() {
			
			var theBio = $(this).parent().parent().clone();
			theBio
				.css('width','')
				.css('margin',0)
				.find(".staffContactBio").css('display','block')
				.end()
				.find('.staffContactBioLnk').remove()
				.end()
				.find('.staffContactImage').css('display','block')
				.end()
				.find('.bioContent').css('width', '600px');
			
			var dialogwindow = $("#dialog-window");
			if (dialogwindow.length > 0) {
				//if dialogwindow already exists, remove it
				dialogwindow.remove();
			}
			
			dialogBox = $('<div style="display:hidden;" id="dialog-window"></div>').appendTo('body').dialog({
				width: 800,
				height: 600,
				modal: true,
				dialogClass: 'diagBox',
				open: function(){
					//make sure flash doesn't bleed
					$("object", $("#mainContainer")).hide().addClass('tempDiagHide');
				},
				close: function(){
					//make sure flash doesn't bleed
					$("tempDiagHide", $("#mainContainer")).show();
				}
			}).append( theBio );
			
			return false;
		});
	}
	
	
	//event registration
	if ($("#eventRegisterBtn").length > 0) {
		
		$("#eventRegisterBtn").click(function() {
			var theURL = $(this).attr('ajxURL');
			var dialogwindow = $("#dialog-window");
			
			if (dialogwindow.length > 0) {
				//if dialogwindow already exists, remove it
				dialogwindow.remove();
			}
			
			dialogBox = $('<div style="display:hidden;" id="dialog-window" title="Event Registration">loading...</div>').appendTo('body').dialog({
				width: 900,
				height: 600,
				modal: true,
				dialogClass: 'diagBox',
				open: function(){
					//make sure flash doesn't bleed
					$("object", $("#mainContainer")).hide().addClass('tempDiagHide');
				},
				close: function(){
					//make sure flash doesn't bleed
					$("tempDiagHide", $("#mainContainer")).show();
				},
				buttons: {
					"Register": function(){
						var theForm = $("#contactFrm");
			
						if ( !requiredFieldCheck(theForm) ) {
							return false;
						}
						
						$.ajax({
							type: "POST",
							url: theForm.attr('action'),
							data: theForm.serializeArray(),
							success: function(response, s){
								
								if (response.CODE == 3) {
									$("#response").text(response.MESSAGE).addClass('ui-state-error');
									$("input[name='captcha']").addClass('ui-state-error').focus();
								} else if (response.CODE == 2 || response.CODE == 2.0){
									dialogBox.dialog( "close" );
									doMessageBox(response.MESSAGE);
									$("#eventRegisterBox").effect('blind', function() {
										$(this).remove();
									});
								}
								
							},
							error: function(h, s, e){
								alert("Error: " + h.status + " " + e);
							}
						});
					},
					Cancel: function(){
						dialogBox.dialog("close");
					}
				}
			}).load(theURL, {}, function(responseText, textStatus, XMLHttpRequest){
				configNodeModule($("#addressTable"));
			});
			
		});
		
	}
	
	//volunteer signup
	if($("#volunteerSubmit").length > 0){
		
		//volunteer submit button
		$("#volunteerSubmit").button().click(function(e){
			
			e.preventDefault();
			
			var theForm = $("#contactFrm");
			
			if ( !requiredFieldCheck(theForm) ) {
				return false;
			}
			
			$.ajax({
				type: "POST",
				url: theForm.attr('action'),
				data: theForm.serializeArray(),
				success: function(response, s){
					if (response.CODE == 2 || response.CODE == 2.0){
						theForm.fadeOut("fast",function(){
							$("#response").text(response.MESSAGE).addClass('ui-state-highlight');
							theForm.remove();
						});
					} else if (response.CODE == 3) {
						$("#response").text(response.MESSAGE).addClass('ui-state-error');
						$("input[name='captcha']").addClass('ui-state-error').focus();
					} else{
						$("#response").text(response.MESSAGE).addClass('ui-state-error');
					}
				},
				error: function(h, s, e){
					alert("Error: " + s + " " + e);
				}
			});
		});
	}
	
	
	
	//config calendar
	function configCalendar() {
		var eventCalendar = $("#eventCalendar");
		var cids = eventCalendar.attr('cids');
		var eventURL = eventCalendar.attr('eventURL');
		var eventsArry = [];
		
		if ($('.calendarFilterItem', $("#calendarFilter")).length > 0) {
			$('.calendarFilterItem:checked', $("#calendarFilter")).each(function () {
				eventsArry.push($(this).val());
			});
			
			$('.calendarFilterItem', $("#calendarFilter")).click(function() {
				if ($(this).attr('checked') == true) {
					eventCalendar.fullCalendar('addEventSource',$(this).val());
				} else {
					eventCalendar.fullCalendar('removeEventSource',$(this).val());
				}
			});
			
			$("#calendarFilterSelect", $("#calendarFilter")).change(function() {
				$("#calendarFilterSelectItem").attr('checked', false);
				eventCalendar.fullCalendar('removeEventSource',$("#calendarFilterSelectItem").val());
				$("#calendarFilterSelectItem").val( $(this).val() );
				if ($("#calendarFilterSelectItem").val() != "") {
					$("#calendarFilterSelectItem").attr('checked', true);
					eventCalendar.fullCalendar('addEventSource',$(this).val());
				}
			});
			
		} else {
			eventsArry.push(eventCalendar.attr('ajxURL'));
		}
		
		
		eventCalendar.fullCalendar({
			editable:false,
			eventSources: eventsArry,
			eventColor: '#ffffff',
			eventTextColor: '#0B469E',
			timeFormat: 'hh:mmtt',
			header: {
				left: 'prev,next today',
				center: 'title',
				right: 'month,agendaWeek,agendaDay'
			},
			loading: function(bool) {
				if (bool) {
					$('#calendarLoading').show();
				} else {
					$('#calendarLoading').hide();
				}
			},
			eventClick: function(calEvent, jsEvent, view) {
				
				window.location.href=eventURL+'/eid/'+calEvent.id+'/cdt/'+Math.round(calEvent.start / 1000);
				return false;
		
		    }
		});
		
	}
	
	//setup calendar
	if ( $("#eventCalendar").length > 0 ) {
		configCalendar();
	}
	
	
	
	
//---------------------reusable address form start---------------------
	if ($("#addressTable").length > 0) {
		configNodeModule($("#addressTable"));
		//additional info node config
		configNodeModule($("#additionalInfoTable"));
	}
//---------------------reusable address form end---------------------




//-------------------------------------------------reusable node module form start-------------------------------------------------
	function configNodeModule(theParent) {
		$(".addNodeLnk", theParent).click(function(){
		
			var theNode = $("#" + $(this).attr('node')).clone();
			var lastNode = $(this).prev().attr('id');
			var nextNode = parseInt(lastNode.substring(11, lastNode.length)) + 1;
			
			//set new node id
			theNode.attr('id', lastNode.substring(0, 11) + nextNode);
			
			//reset node form vals
			$(":input", theNode).val("").removeAttr('selected').removeAttr('checked');
			
			//add remove link for node
			theNode.append($(' <a href="" class="removeNodeLnk">remove</a>'));
			
			//append node before add link
			theNode.insertBefore($(this));
			
			return false;
		});
		
		$(".removeNodeLnk", theParent).live('click', function(){
			$(this).parent().remove();
			return false;
		});
	}
//-------------------------------------------------reusable node module form end-------------------------------------------------

	
	
	
	
	
	
	//global message box
	function doMessageBox(theMessage) {
		var alertMessageBox = $('<div id="alertMessageBox"><span class="ui-icon ui-icon-alert floatL"></span>'+theMessage+'</div>')
				.prependTo( $("#top-nav-bread-crumbs") )
				.addClass("ui-state-highlight")
				.slideDown().delay(8000).slideUp('fast');
	}
	
	
	function requiredFieldCheck(theForm) {
		var formPassed = true;
		
		$("input[class~='requiredField'],textarea[class~='requiredField'],select[class~='requiredField']",theForm).each(function() {
			if ($(this).val() == "" || $(this).val() == "0") {
				
				$(this).addClass('ui-state-error')
						.focus()
						.click(function() {
							$(this).removeClass('ui-state-error');
						});
				
				formPassed = false;
			}
		});
		
		return formPassed;
	}
		
	
	
	
	

	//partner submit
	if ($("#submitOrganizationFrmBtn").length){
		
		
		//volunteer submit button
		$("#submitOrganizationFrmBtn").button().click(function(e){
			
			e.preventDefault();
			
			var theForm = $("#organizationFrm");
			
			if ( !requiredFieldCheck(theForm) ) {
				return false;
			}
			
			$.ajax({
				type: "POST",
				url: theForm.attr('action'),
				data: theForm.serializeArray(),
				success: function(response, s){
					if (response.CODE == 2 || response.CODE == 2.0){
						theForm.fadeOut("fast",function(){
							$("#response").text(response.MESSAGE).addClass('ui-state-highlight');
						});
					} else if (response.CODE == 3) {
						$("#response").text(response.MESSAGE).addClass('ui-state-error');
						$("input[name='captcha']").addClass('ui-state-error').focus();
					} else{
						$("#response").text(response.MESSAGE).addClass('ui-state-error');
					}
				},
				error: function(h, s, e){
					alert("Error: " + s + " " + e);
				}
			});
		});
							
	}
	
	
	//googleMap
	if ($("#map_canvas").length > 0){
		var map_canvas = $("#map_canvas");
		oh = {};
		oh.googleMap = function(){
		
			neighborhoods = [];
			content = [];
			
			//Grab the locations.
			$.ajax({
				type: "GET",
				url: map_canvas.attr('ajxURL'),
				success: function(data){
					var arrLength = data.length;
					
					for(i=0;i<arrLength;i++){
						//codeAddress(data[i]);
						neighborhoods[i] = new google.maps.LatLng(data[i][0],data[i][1]);
						content[i] = data[i][2];
					}
				}
			});
			
			var infoURL = map_canvas.attr('infoURL');
			var markers = [];
			var map;
			var usa = new google.maps.LatLng(37.09024, -95.71289100000001);
			
			var image = new google.maps.MarkerImage(map_canvas.attr('iconimg'),
				// This marker is 20 pixels wide by 32 pixels tall.
				new google.maps.Size(20, 32),
				// The origin for this image is 0,0.
				new google.maps.Point(0,0),
				// The anchor for this image is the base of the flagpole at 0,32.
				new google.maps.Point(0, 32));
			var shadow = new google.maps.MarkerImage(map_canvas.attr('iconshadowimg'),
				new google.maps.Size(37, 32),
				new google.maps.Point(0,0),
				new google.maps.Point(0, 32));
			var shape = {
				coord: [1, 1, 1, 20, 18, 20, 18 , 1],
				type: 'poly'};
			
			function initialize() {
							
				var stylez = [
				  {
				    featureType: "administrative.locality",
				    elementType: "labels",
				    stylers: [
				      { visibility: "off" }
				    ]
				  },{
				    featureType: "administrative.country",
				    elementType: "labels",
				    stylers: [
				      { visibility: "off" }
				    ]
				  },{
				    featureType: "administrative.province",
				    elementType: "labels",
				    stylers: [
				      { visibility: "off" }
				    ]
				  }
				];
				
				var mapOptions = {
					scrollwheel: false,
					zoom: 4,
					mapTypeControlOptions: {
				       mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'ohMap']
				    },
					center: usa
				};
				
				map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
				
				var styledMapOption = {
					name: "Operation HOPE"
				}
				
				var ohMapType = new google.maps.StyledMapType(stylez, styledMapOption);
				
				map.mapTypes.set('ohMap', ohMapType);
				map.setMapTypeId('ohMap');
				
				infoWindow = new google.maps.InfoWindow();
				
			}
			
			function drop() {
				for (var i = 0; i < neighborhoods.length; i++) {
					addMarker(i);
				}
			}
			
			
			function addMarker(num) {
				var marker = new google.maps.Marker({
		            map: map, 
		            position: neighborhoods[num],
					shadow: shadow,
			        icon: image,
			        shape: shape,
		            animation: google.maps.Animation.DROP
		        });
		        
		        //Creates the info window for the current marker being added.
		        marker.info = new google.maps.InfoWindow({
		        	content: ""+content[num]
		        });
				
				google.maps.event.addListener(marker, 'click', function() {
					
					if (!isNaN(parseInt(marker.info.content))) {
						$.ajax({
							type: "GET",
							url: infoURL,
							data: ({cid: marker.info.content}),
							success: function(response, s){
								marker.info.setContent(response);
							},
							error: function(h, s, e){
								alert("Error: " + s + " " + e);
							}
						});
					}
					
					// When clicked, open an Info Window  
					marker.info.open(map, marker);
					
					
				}); 
			}
			
			initialize();
			setTimeout(function() {
						drop();
						//codeAddress();
					}, 1000);
		
		}
		oh.googleMap();
	}
	
});

