$(document).ready(function(){

//start homepage banner cycle
  $('#Banner').cycle({
				delay: 1000,
				timeout: 8000,
				speed: 1200,
				pause: 1,
				prev: '#prev',
				next: '#next'
		    });

//--------Get us to the right page------------------
  	
	//check for hash
	
	if (location.hash != null && location.hash != ""){
		var mainpagehash = location.hash;
			
				//look for subpage '-'
				var mainpagehashdash = mainpagehash.search("-");
				
				//if no subpage
				if (mainpagehashdash == "-1"){
					
					var mainpageclass = mainpagehash.replace("#", "");
					mainpageclass = mainpageclass;
				}
			  else{
					//extract pageclass for tab selection and subpage data
					var subpageclass = mainpagehash.substring(mainpagehashdash+1);
					mainpageclass = mainpagehash.replace("#", "");
					
					mainpageclass = mainpageclass.substring(0, mainpagehashdash-1);
					mainpageclass = mainpageclass;
					
			    }
		
		

	}
	else  { 
		mainpageclass = "home";
	}
	loadpage(mainpageclass);
	


//initialize remote_history watching
$.ajaxHistory.initialize();


//initial all links with class=media to display media linked to




 });
//--------end of document ready
 
 
 
 


 //Load the clicked page
function loadpage(page){
 var wp_root = "http://www.burienfm.org/WP/wp-content/themes/BurienFM/";

	
 $('#Content').fadeOut("slow", function(){
	$(".tablinks").fadeOut(300);
	
	//set tabs
		//main
			var pagehash = location.hash;
			
				//look for subpage '-'
				var pagehashdash = pagehash.search("-");
				
				//if no subpage
				if (pagehashdash == "-1"){
					
					pageclass = pagehash.replace("#", "");
				}
			  else{
					//extract pageclass for tab selection and subpage data
					var subpageclass = pagehash.substring(pagehashdash+1);
					pageclass = pagehash.replace("#", "");
					pageclass = pageclass.substring(0, pagehashdash-1);
			    }
				 
				//set default page
				if (!pagehash){pageclass= "home";}
			 
			 //remove and set selected main tab
			 $(".selected").removeClass("selected");
			 
			 $("."+pageclass).addClass("selected");
	 			
	 


	 $("#Loader").fadeIn("fast");
		  
		  //animate bars
		   if (page !="home" && page != "contact"){
			  
			 	
				
				$(".tablinks").load(wp_root+"sublinkpuller.php?page="+page+"&subpage="+subpageclass, function(){
							
						//action 2 = delay tabbar to give banner time, show tabbar
							//check to see if banner is already hidden, if so then tabbar should already be displayed, dont run function
							
								 showtabbar();
						
							
											
							//set secondary link tab
								 $("."+subpageclass).addClass("selected");
							
							//action 3 = delay tablinks to give tabbar time, show tablinks				
							setTimeout("$('.tablinks').fadeIn(500)", 2000);
							
							//action4 = delay loading content to give tabbar time, show content
							
							setTimeout((function(){loadcontent(page, subpageclass);}), 3000);
																				 
										
					});
								
						
			}
			else{
				if ( $(".tablinks").is(':visible') ){
					$(".tablinks").fadeOut("fast", function(){
						$(".tabbar").animate({"height": "0px", "opacity": "0%"}, "slow", "swing", function(){
								$(this).hide();
								 
											 //action4 = delay loading content to give tabbar time, show content
												  setTimeout((function(){loadcontent(page, subpageclass);}), 3000);
							});
						});
				}
				else{
					loadcontent(page, subpageclass);
				}
			}

		
	   });
 };
 
 
 function hidebanner(){
 
    //animate banner if visible	
		if ( $(".banner").is(':visible') ){
				 $(".banner").animate({"height": "0px", "opacity": "0%"	}, 1000, "swing", function(){
						$(this).hide();
						//alert("banner animated");
						});
						return true;
			}
		else{
				//alert("banner not animated");
 				return false;
			}
 };

function showtabbar(){

		//animate tabbar if hidden
			if ( $(".tabbar").is(':hidden') ){
					setTimeout("animatetab()", 1500);
								//alert("animated bar");
								return true;
								
			}
			else{
				//alert("not animated bar");
				return false;
			}
};

function animatetab(){
$(".tabbar").animate({"opacity": "100%" }, "slow", "swing")
								.animate({ "height": "28px" }, "slow");

};

function loadcontent(pagetoload, subpage){
//load content
 var wp_root = "http://www.burienfm.org/WP/wp-content/themes/BurienFM/";
//create random variable to eliminate caching
	var currentTime = new Date();
	var RandomVariable = currentTime.getTime();
	
	
//	alert(pagetoload +" "+subpage);
	
 if (pagetoload == "calendar" && subpage==undefined){
	 $("#Content").load(wp_root+"calendar.php?random="+RandomVariable, function(){	
				$("#Loader").fadeOut("fast", function(){
					$("#Content").fadeIn("fast");
				
				
				});		
			});
 }
 else if (pagetoload == "contact" && subpage==undefined){
	 $("#Content").load(wp_root+"contact.php?random="+RandomVariable, function(){	
				$("#Loader").fadeOut("fast", function(){
					$("#Content").fadeIn("fast");
				
				
				});		
			});
 }
  else if (pagetoload == "contact" && subpage=="register"){
	 $("#Content").load(wp_root+"register.php?random="+RandomVariable, function(){	
				$("#Loader").fadeOut("fast", function(){
					$("#Content").fadeIn("fast");
				
				
				});		
			});
 }
 else if (pagetoload == "home"){
	  $("#Content").load(wp_root+"homepage.php?random="+RandomVariable, function(){	
	 	 $("#Welcome").load(wp_root+"pagepuller.php?page="+pagetoload+"&subpage="+subpage+"&random="+RandomVariable, function(){	
				$("#Loader").fadeOut("fast", function(){
					$("#Content").fadeIn("fast",function(){
														 
				CalIntID = setInterval("CalReady()",1000);
				
					
					});
				
				});		
			});
	  });
 }
  else if (pagetoload == "media" && subpage == "Sermons"){
	  
	  $("#Content").load(wp_root+"sermons.php?random="+RandomVariable, function(){	
				$("#Loader").fadeOut("fast", function(){
					$("#Content").fadeIn("fast");
				//initialize media playback
			$('a.media').media({ width: 300, height: 20 });

				archiveMenu();
				});		
			});

 }
 
 else{
	   $("#Content").load(wp_root+"pagepuller.php?page="+pagetoload+"&subpage="+subpage+"&random="+RandomVariable, function(){	
				$("#Loader").fadeOut("fast", function(){
					$("#Content").fadeIn("fast");
				
				
				});		
			});
 }

};



function sendcontact(myform){
	//Form Validate - if not valid then stop		
		
		
		var options = {
			messages:{
				username: "required",
				useremail: "Invalid email",
				subject: "required",
				message: "required"
			}
		};
		if ( $("#"+myform).validate(options).form() == false)
			{
				//alert("fail");
			return false;
			}
			
			
			$("#"+myform).ajaxSubmit({
					//target: '#TestOut',
					beforeSubmit: function(formArray) { },
					error:function (XMLHttpRequest, textStatus, errorThrown) {$("#ContactFormDiv").html("There was an error sending your message. Please try again.");},
					success: function(html) {
						//alert(html);
								$("#ContactFormDiv").html("Thank you for contacting us. We look forward to responding to you as soon as possible!");
								}
								 });
			
};

function archiveMenu(){
	//hide all sub menus to start
	$('.year').children('.level1').hide();	
	$('.year > ul > .month').children('.level2').hide();
	//show first year expanded
	$('.year:eq(0)').children('.level1').slideDown();	
	
	//display year onclick
	$('.year > a.head1').click(function(){
		//get ID of current year being clicked
		var yearID = $(this).parent("li").attr("id");						
		$('#'+yearID).children('.level1').slideToggle(function(){	
			//hide all months
			$('.year > ul > .month').children('.level2').hide();
		});
	
	});
	
	//display month onclick
	$('.month > a.head2').click(function(){
		//get ID of current month being clicked
		var monthID = $(this).parent("li").attr("id");
		$('#'+monthID).children('.level2').slideToggle();	
		
		
	});
	
};






function CalReady(){
	if(SetCal == "True"){
		
		clearInterval(CalIntID);
		
		loadDeveloperCalendar();
	}
	else{
		
	}
	
}

/**
 * Loads the Google Developers Event Calendar
 */
function loadDeveloperCalendar() {
	
  loadCalendarByAddress('burienfm.org_74hldthpej5oj91gv9ru8e0e80@group.calendar.google.com');
 // loadCalendarByAddress('developer-calendar@google.com');
}

/**
 * Adds a leading zero to a single-digit number.  Used for displaying dates.
 */
function padNumber(num) {
  if (num <= 9) {
    return "0" + num;
  }
  return num;
}

/**
 * Determines the full calendarUrl based upon the calendarAddress
 * argument and calls loadCalendar with the calendarUrl value.
 *
 * @param {string} calendarAddress is the email-style address for the calendar
 */ 
function loadCalendarByAddress(calendarAddress) {
  var calendarUrl = 'http://www.google.com/calendar/feeds/' +
                    calendarAddress + 
                    '/public/full';
  loadCalendar(calendarUrl);
}

/**
 * Uses Google data JS client library to retrieve a calendar feed from the specified
 * URL.  The feed is controlled by several query parameters and a callback 
 * function is called to process the feed results.
 *
 * @param {string} calendarUrl is the URL for a public calendar feed
 */  
function loadCalendar(calendarUrl) {
	
  var service = new 
      google.gdata.calendar.CalendarService('rsr-training');
  var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
  query.setOrderBy('starttime');
  query.setSortOrder('ascending');
  query.setFutureEvents(true);
  query.setSingleEvents(true);
  query.setMaxResults(8);

  service.getEventsFeed(query, listEvents, handleGDError);
}

/**
 * Callback function for the Google data JS client library to call when an error
 * occurs during the retrieval of the feed.  Details available depend partly
 * on the web browser, but this shows a few basic examples. In the case of
 * a privileged environment using ClientLogin authentication, there may also
 * be an e.type attribute in some cases.
 *
 * @param {Error} e is an instance of an Error 
 */
function handleGDError(e) {

  document.getElementById('jsSourceFinal').setAttribute('style', 
      'display:none');
  if (e instanceof Error) {
    /* alert with the error line number, file and message */
    alert('Error at line ' + e.lineNumber +
          ' in ' + e.fileName + '\n' +
          'Message: ' + e.message);
    /* if available, output HTTP error code and status text */
    if (e.cause) {
      var status = e.cause.status;
      var statusText = e.cause.statusText;
      alert('Root cause: HTTP error ' + status + ' with status text of: ' + 
            statusText);
    }
  } else {
    alert(e.toString());
  }
}

/**
 * Callback function for the Google data JS client library to call with a feed 
 * of events retrieved.
 *
 * Creates an unordered list of events in a human-readable form.  This list of
 * events is added into a div called 'events'.  The title for the calendar is
 * placed in a div called 'calendarTitle'
 *
 * @param {json} feedRoot is the root of the feed, containing all entries 
 */ 
function listEvents(feedRoot) {

  var entries = feedRoot.feed.getEntries();
 //document.write(entries);
  var eventDiv = document.getElementById('CalEvents');
  if (eventDiv.childNodes.length > 0) {
    eventDiv.removeChild(eventDiv.childNodes[0]);
  }	  
  /* create a new unordered list */
  var ul = document.createElement('ul');
  /* set the calendarTitle div with the name of the calendar 
  document.getElementById('calendarTitle').innerHTML = 
    "<h3>Upcoming Events</h3>" */
  /* loop through each event in the feed */
  var len = entries.length;
  for (var i = 0; i < len; i++) {
    var entry = entries[i];
    var title = entry.getTitle().getText();
    var startDateTime = null;
    var startJSDate = null;
	var timeString;
    var times = entry.getTimes();
    if (times.length > 0) {
      startDateTime = times[0].getStartTime();
      startJSDate = startDateTime.getDate();
    }
    var entryLinkHref = null;
    if (entry.getHtmlLink() != null) {
      entryLinkHref = entry.getHtmlLink().getHref();
    }
    var dateString = (startJSDate.getMonth() + 1) + "/" + startJSDate.getDate();
    if (!startDateTime.isDateOnly()) {
		
			//Convert to standard time
			var ampm = "am";
			var mh = startJSDate.getHours();
			if(mh > 12) {
			mh = mh - 12; //standard hours
			ampm = "pm";
			}
			
      timeString = mh + ":" + 
          padNumber(startJSDate.getMinutes())  + ampm;
    }
    var li = document.createElement('li');
	//Create substring of Title for formatting
	if (title.length > 17){
		title = title.substring(0,17) + "...";
	}
    /* if we have a link to the event, create an 'a' element */
    if (entryLinkHref != null) {
      entryLink = document.createElement('a');
      entryLink.setAttribute('href', '#');
	  entryLink.setAttribute('onclick', "window.open('"+entryLinkHref+"','rsrEvent','width=600,height=300,resizable=yes, scrollbars=yes'); return false;");
      entryLink.appendChild(document.createTextNode(title));
      li.appendChild(entryLink);
      li.appendChild(document.createTextNode(' - ' + dateString + ' ' + timeString));
    } else {
      li.appendChild(document.createTextNode(title + ' - ' + dateString + ' ' + timeString));
    }	    

    /* append the list item onto the unordered list */
    ul.appendChild(li);
  }
  eventDiv.appendChild(ul);
}