//open chat window

function openChat() {
	
 							var centerWidth = (screen.width - 465) / 2;
                            var centerHeight = (screen.height - 315) / 2;

                            var slipWindow =  window.open('','Parachute_Band_Live_Chat','width=465,height=315,left=' + centerWidth + ',top=' + centerHeight);
                            var html = '<embed src="http://widget.meebo.com/mm.swf?pjGBRewODz" type="application/x-shockwave-flash" width="100%" height="95%"></embed>';
                            slipWindow.document.open();
                            slipWindow.document.write(html);
                            slipWindow.document.close();
							try
							{
								slipWindow.document.title = "Parachute Band - Live Chat";
							}
							catch(err)
							{
							}

	
}

//start slideshow
function startSlideShow() {

	// randomize the images
		 $("#header_images ul").randomize("li");
		 $("#header_images ul").randomize("li");
		 $("#header_images ul li.show").removeClass("show");
		 jQuery('#header_images ul li:first').addClass("show");
		
	//Set the opacity of all images to 0
	$('#header_images ul li').css({opacity: 0.0});
	
	//Get the first image and display it (gets set to full opacity)
	$('#header_images ul li:first').css({opacity: 1.0 });
	//Call the rotator function to run the slideshow, 6000 = change to next image after 6 seconds
	setInterval('slide()',7500);
	
}

function slide() {	
	//Get the first image
	var current = ($('#header_images ul li.show')?  $('#header_images ul li.show') : $('#header_images ul li:first'));

	//Get next image, when it reaches the end, rotate it back to the first image
	var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('#header_images ul li:first') :current.next()) : $('#header_images ul li:first'));	
	
	//Set the fade in effect for the next image, the show class has higher z-index
	next.css({opacity: 0.0})
	.addClass('show')
	.animate({opacity: 1.0}, 1000);

	//Hide the current image
	current.animate({opacity: 0.0}, 1000)
	.removeClass('show');
	
};
// ------ end slideshow

function getYouTubeVideo() {
	//clear the content in the div for the next feed.
	$("#youtube_video").empty();
 
	//use the JQuery get to grab the URL from the selected item, put the results in to an argument for parsing in the inline function called when the feed retrieval is complete

 $.get('../proxy.php?url=http://gdata.youtube.com/feeds/base/users/parachuteband/uploads?alt=rss&amp;v=2&amp;orderby=published&amp;client=ytapi-youtube-profile', function(d) {
 //$.get("youtube.xml", function(d) {
		//find each 'item' in the file and parse it
		$(d).find('item').each(function() {
 
			//name the current found item this for this particular loop run
			var $item = $(this);
			// grab the post title
			var title = $item.find('title').text();
			var guid =  $item.find('guid').text().split(":");
			guid = guid[1].split("/");
			guid = guid[guid.length-1];
			$('#youtube_video').flash({
   			 src: 'http://www.youtube.com/v/' + guid + '&amp;hl=en_US&amp;fs=1&amp;rel=0',
   			 width: 308,
   			 height: 246,
			 wmode: "transparent",
			 allowFullScreen: "true"
			});
			return false; 
		});
	});
 
};

function getTwitter() {
	$.get('templates/parachuteband/proxy.php?url=http://twitter.com/statuses/user_timeline/15888638.rss', function(d) {
 //$.get("youtube.xml", function(d) {
		//find each 'item' in the file and parse it
		$(d).find('item').each(function() {
 			var theItem = $(this);
			var title = theItem.find('title').text();
			title = title.replace("parachuteband: ","");
			
			var date = new Date(theItem.find('pubDate').text());
			var alink = theItem.find('link').text();
			//alert(date);
			
			$("#tweet_text").empty().append("<a href=\"" + alink + "\">" + title + "</a>");
			
			if((new Date().getTime() - new Date(theItem.find('pubDate').text()).getTime()) > 86400000) // greater than number of milliseconds in a day
			{
				$('.tweet_sent').countdown({since: date, layout: ' Sent {dn} {dl} ago'});
			}
			else if((new Date().getTime() - new Date(theItem.find('pubDate').text()).getTime()) > 3600000) // greater than number of milliseconds in an hour
			{
				$('.tweet_sent').countdown({since: date, layout: ' Sent {hn} {hl} ago'});
			}
			else
			{
				$('.tweet_sent').countdown({since: date, layout: ' Sent {mn} {ml} ago'});
			}
			
			if(title != "")
			{
				
				$("#tweet_text").truncate(85);
				return false;
			}
 		});
		
		});
		

};

function getFacebookEvents() {


 $.get("facebook_events.xml", function(d) {
 var count = 0;
 
 /*d.sort(sortEvents);
 	function sortfunction(a, b){
		
		return (a. - b) //causes an array to be sorted numerically and ascending
	}
	*/
	//alert($(d).find('item').size());
		//find each 'item' in the file and parse it
		var tmpCount = 0;
		var theDateList = new Array();
		var currentTime = new Date().getTime();
		$(d).find('item').each(function() {
		 	
			if($(this).find('name').text() != "")
			{
			
				if(Math.round(new Date().getTime() / 1000) < parseInt($(this).find('start_time').text()))
				{
					// it is upcoming (i.e. greater than current time
					// populate the array
					theDateList[tmpCount] = parseInt($(this).find('start_time').text());
					
					tmpCount++;
					if(tmpCount > 3)
					{
						//return false;
					}
				}
				
			}
		 });
		
		// sort the list
		 theDateList.sort();
		 theDateList.reverse();
		 if(theDateList.length > 5)
		 {
		 	theDateList.reverse();
		 	theDateList.splice(5, theDateList.length-5);
		 } else
		 {
		 	theDateList.reverse();
		 }
		 
		 
		 
		
		for(i=0;i<theDateList.length;i++)
		 	{
		
				$(d).find('item').each(function() {
					
					//name the current found item this for this particular loop run
					var $item = $(this);
					// grab the post title
					//var title = $item.find('title').text();
					var content =  $item.find('name').text();
					var locationInfo = content.split(",");
					content = locationInfo[0];
					
					var cityState = "";
					var country = "";
					if(locationInfo.length == 3)
					{
						cityState = locationInfo[1];
						country = locationInfo[2];
						content = locationInfo[1] + ", " + locationInfo[2];
					}
					
					if(content != "" && $item.find('start_time').text() == theDateList[i])
					{
						var month=new Array(12);
						month[0]="Jan";
						month[1]="Feb";
						month[2]="Mar";
						month[3]="Apr";
						month[4]="May";
						month[5]="Jun";
						month[6]="Jul";
						month[7]="Aug";
						month[8]="Sep";
						month[9]="Oct";
						month[10]="Nov";
						month[11]="Dec";
						var myDate = null;
						try {
						myDate = new Date($item.find('start_time').text() *1000);
						myDate = myDate.getTime() + (myDate.getTimezoneOffset() * 60000);
						myDate = new Date(myDate + (3600000*'-7'));
						myDate = myDate.getDate() + " " + month[myDate.getMonth()] + " " + myDate.getFullYear();
						}
						catch (err) { 
						myDate = "Date unknown";
						}
						$("#home_tour_output .loading_text").animate({opacity: 0.0}, 500).hide(800, function() { $("#tour_dates_view_more").show(400) });
						$("#home_tour_output").append("<h3>" + myDate + "</h3>");
						$("#home_tour_output").append("<p>" +  content + "</p>");
						$("#home_tour_output p").truncate(25);
						
						count++;
						if(count == 4) { return false; }
					}
					
				});
			} // end for look theDateList
	
	});
/*	This is the old version but now uses a go-between
	FB.ensureInit(function() {  
	FB.Facebook.apiClient.events_get(
     6263163989,
     '',
     0,
     0,
     '',
     function(result){
          alert(result);
     });
	 });*/
};

$(document).ready(function() {

// randomize function
	$.fn.randomize = function(childElem) {
	  return this.each(function() {
		  var $this = $(this);
		  var elems = $this.children(childElem);
	
		  elems.sort(function() { return (Math.round(Math.random())-0.5); });  
	
		  $this.remove(childElem);  
	
		  for(var i=0; i < elems.length; i++)
			$this.append(elems[i]);      
	
	  });    
	}
	
	// Open external links offsite
	$("a").filter(function() {
    		return this.hostname && this.hostname !== location.hostname;
	}).attr('target', '_blank');

	// Preload image rollovers
//	$.preloadCssImages();
	//Start slideshow
	startSlideShow();
	//Load newest YouTube
	//getYouTubeVideo(); // this is the old system and not used any more :(
	//Get Tour Dates
	getFacebookEvents();
	//Get Twitter
	getTwitter();
	//Setup Mp3 player
	$('#toplinks_mp3player').flash({
   			 src: 'templates/parachuteband/javascript/mp3player.swf',
   			 width: 231,
   			 height: 24,
			 wmode: "transparent",
			 allowFullScreen: "true"
			});
			
		//Mailing list
		$('body').append('<div id="mailing_list_shadow"><!-- the black page shadow --></div><div id="mailing_list_wrap"> 	<div id="mailing_list_box">         	<form id="mailing_list_form" target="submitFrame" action="templates/parachuteband/process_form.php" method="post"> <div class="bookingform"> <p class="caption">I have read and agreed to Parachute Music’s <a href="http://www.parachutemusic.com/index.php?option=com_content&task=view&id=30&Itemid=111">Privacy Policy</a>, and I\'d like Parachute BAND to contact me with updates from time to time.</p> <div class="bookingform_cell"> <p><span class="red">*</span>First Name</p> <p><input name="FirstName" type="text" /></p> </div> <div class="bookingform_cell"> <p><span class="red">*</span>Last Name</p> <p><input name="LastName" type="text" /></p> </div> <div class="bookingform_cell"> <p><span class="red">*</span>City</p> <p><input name="City" type="text" /></p> </div> <div class="bookingform_cell"> <p><span class="red">*</span>Country</p> <p><input name="Country" type="text" /></p> </div> <div class="bookingform_cell"> <p><span class="red">*</span>Email</p> <p><input name="Email" type="text" /></p> </div> <div class="bookingform_cell"> <p>Mobile Phone</p> <p><span class="red"></span><input name="Mobile" type="text" id="Mobile" /></p> </div> <div class="bookingform_cell bookingform_cell_submit"> <p><input class="bookingform_submit" type="submit" value="Submit" /></p> </div>  </div></form>         </div>     </div> ');
	$('#mailing_list_box').append("<a id=\"mailing_list_close\"><span>Close</span></a>");
		$('body').append(' <iframe id="submitFrame" name="submitFrame" style="width:0; height:0; display:none;"></iframe> ');

	//Set the booking form post url (prevent spam)
		$("#bookingform").attr("action","/parachuteband/templates/parachuteband/process_form.php");
		$("form").attr("target","submitFrame");
		
		$('#mailing_list_close').click(function() {
		$('#mailing_list_wrap').hide();
		$('#mailing_list_shadow').hide();
	});
		$('#toplinks_livechat').click(function()
											   {
												  openChat(); 
											   });
	$("#toplinks_subscribe").click(function() {
		$('#mailing_list_shadow').show();
		$('#mailing_list_shadow').css('height', $(document).height() + 'px');	
		$('#mailing_list_wrap').show();
	});
	
	
	
	// Subscription rollover
	$("#toplinks_subscribe").hover(
		function() {
			$(this).stop().animate({"width": "293px"}, "slow");
		},
		function() {
			$(this).stop().animate({"width": "30px"}, "slow");
		});
		
		//----------
	
	$("#tweet_text").truncate( 85 )
		
	$("#tweet p").animate({opacity: 0.0, marginTop: "10px"}, 0)
		.delay(600)
			.animate({opacity: 1.0, marginTop: "18px"}, 400);
			
	// Create nice menu effect		
	$("#menu a").hover(
		function() {
			$(this).css({opacity: 0}).animate({"opacity": "1"}, "slow");
		},
		function() {
			$(this).animate({"opacity": "0.5"}, "slow").animate({"opacity": "1"}, "fast");
	});
	
	// Social network link rollover
	$("#header_links .darken").hover(
		function() {
			$(this).animate({"opacity": "0.5"}, "slow");
		},
		function() {
			$(this).animate({"opacity": "1"}, "fast");
	});
	
	// The mailing list popup
		if($.cookie("has-visited-pb") == null)
	    {
			setTimeout(function(){
                $('#mailing_list_shadow').show();
			 	$('#mailing_list_shadow').css('height', $(document).height() + 'px');	
				$('#mailing_list_wrap').show();
				$.cookie("has-visited-pb", 'true', { expires: 90 });
               },10000);
			
		
		}
		if($.cookie("has-signed-up") != null)
	    {
			//$("#toplinks_subscribe").hide();
			//$("#toplinks_livechat").show();
			$.cookie("has-signed-up", 'true', { expires: 365 });
		
		}
	
	

		
	$("#home_news .home_title").truncate(50);
	
	$("#home_news .date").each(function()
	{
		var month=new Array(12);
		month[0]="Jan";
		month[1]="Feb";
		month[2]="Mar";
		month[3]="Apr";
		month[4]="May";
		month[5]="Jun";
		month[6]="Jul";
		month[7]="Aug";
		month[8]="Sep";
		month[9]="Oct";
		month[10]="Nov";
		month[11]="Dec";
		myShort = $(this).text().split(" ");
		myShort = myShort[0].split("-");
		
		var theDate = myShort[2] + " " + month[parseInt(myShort[1], 10) - 1] + " " + myShort[0];
		//alert(myShort[1] + " - " + parseInt(myShort[1]) + " - " + theDate);
		$(this).text(theDate);
		
	});
	
	// validation for mailing list box
	$("#mailing_list_form").submit(function() {
					
					var retVal = true;
					 $("#mailing_list_form .bookingform_cell input").not($("#Mobile")).each(function() {
					 	
						
						if($(this).val() == "" || $(this).val() == null)
						{
													
							$(this).animate({ backgroundColor: "red"}, "fast");
							
							retVal = false;
							
						} 
					 
					 })
					 
					 if(retVal)
					 {
						 
						$.cookie("has-signed-up", 'true', { expires: 365 });
						//$("#toplinks_subscribe").hide();
						//$("#toplinks_livechat").show();
					 	$('#mailing_list_box').append("<img class=\"thankyou_msg\" src=\"templates/parachuteband/images/thankyou_signup.gif\" />");
					 	
					 }
					
					
					 return retVal;
					 
					
		}); 
		
		$("#mailing_list_form input").focus(function() {
			$(this).css({ background: 0 });
			return true;
		});

});
