//todo:
//
//autoplay on ipad


var mobile;
var global_lp=0;
var len=180;
var now_playing = {};

var client;
var podcastpage;
var post;


function socialButtons(permalink){
	
	var social_stuff= '<br style="clear:both;">'
        +'<iframe src="http://www.facebook.com/plugins/like.php?href='+permalink+'&amp;layout=button_count&amp;show_faces=false&amp;width=90&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:90px; height:21px;" allowTransparency="true"></iframe>'
        +'<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/tweet_button.html?url='+permalink+'" style="width:130px; height:21px;"></iframe>'

   return social_stuff;
}

//use slug comparison to determine if were on a landing page

function landingPage(id){
	
	var params = $('#item_'+id).data();
	
	params.autoplay = false;
	if(!$('#item_'+id).hasClass('locked')){
	player= new Player(params);
	player.render();
	}
	
	$('body').addClass('landing_page');  
	$('.load_more .loadtext').text('home');
	$('.load_more a').attr('href','/'+document_slug);
	$('.item').unbind();
	$('.share').html(socialButtons(params.permalink));
}
      
/*set up and format podcast page */

function Page () {
	
	this.init = function (){
	
		
		$('.comment_time').each(function(){

             var rawdate = $(this).html();
             
			$(this).html(humane_date(rawdate));

		});
		
		if(expire_before){
			var expiration_date = new Date(expire_before);
			
		    $('.post_date').each(function(){
		    	
		    	var date = new Date($(this).html());
		    
		    	if(date<expiration_date){
		    		
		    		var id = $(this).parents('.item').data('item_id');
		    		$(this).parents('.item').addClass('locked');
		    		
		    		var banner = $('.locked_episode_box').last().clone();
		    		$('#item_title_'+id).after(banner);
		    	}
		    
		    	
		    });
		}
		  
		
		$('body').append('<div id="jquery_jplayer"></div>');
		
		
		$('#jquery_jplayer').jPlayer({
					ready: function () {	
									     
									    },
				 swfPath: 'http://assets.libsyn.com/static/wtfpod/',
				 solution: 'html, flash',
				 //supplied: supplied,
				
				 //preload: 'metadata',
				 preload: 'auto',
				 volume: 1,
				 muted: false,
				 backgroundColor: '#fff',
				 errorAlerts: false,
				 warningAlerts: false
				});
		
		
		


		mobile =  client.isMobile();
	    $('body').addClass((mobile)?'mobilepage':'webpage');
	    $('body').removeClass((mobile)?'webpage':'mobilepage');
	    
	    $('body').addClass((client.isIphone()?'iphone':''));
	    $('body').addClass((client.isPad()?'pad':''));
	    $('body').addClass((client.isAndroid()?'android':''));
	    
		
		$('.more').bind('click',function(){
			$(this).parents('.item').addClass('expanded');
			
		var permalink = $(this).parents('.item').data('permalink');
		
		//console.log($(this).parents('.item').data('url'));
		
		
		
			
			
			$(this).siblings('.share').html(socialButtons(permalink));
			
			
			
			
		});
	
		$('.less').bind('click',function(){
			$(this).parents('.item').removeClass('expanded');
		});
	
	    var search = function(id){
	    	
	    	window.location = '/'+document_slug + '/search/' + $('#'+id).val();
	    	
	    }
	    
	    var gohome = function(e) {
	    	
	
	    	if($(e.target).parents('#social_buttons').length>0 || $(e.target)[0].id=='social_buttons'){
	    		return;
	    	}
	    	window.location = '/'+document_slug
	    }
	    
	    $('#show_title').bind('click',gohome);
	    
	    $('.search_button').live('click',function(e){
	    	
	    	var searchfield_id = (e.currentTarget.id=='modal_search_button') ? 'modal_search_input' : 'search_input'
	    	
	    	search(searchfield_id);
	    	
	    });
	
		$('#about').bind('click',function(){
			
		        $('.show_description').show();	
	
			
		});

	    $('.searchbox').live('keyup',function(e) {
	    	  
		      if(e.keyCode == 13) {
		      	search(e.currentTarget.id);
			  }
		});
		
		$('.item:first').addClass('first_post');
		
	
		if ($('.item').length == episode_count){	
			$('.load_more').hide();
		}
	
		
		$('.play_button_text').each(function(){
    	
    	var file_class = $(this).parents('.item').data('file_class')
    	var button_text = '';
    	
    	if(!file_class){
    	         button_text = 'read';
        
    	}else{
        	
        	if(file_class=='video'){
        		button_text = 'watch';
        	}
        	
        	if(file_class=='audio'){
        		button_text = 'listen';
        	}
        	
        	
        }
        
    	$(this).text(button_text);
    	
    	
    	
    });
	
    $('.title a').each(function(){
    	
    	var max_length = 70;
      
    	var title_string = $(this).html();
  
    	if(title_string.length>max_length){
    		
           var title_string = title_string.substring(0,max_length)+'...';
    	}
    	
    	$(this).html(title_string);
    	

    });
    
    
    $('.description_clean').each(function(){
    	
    	$(this).append('<br><span class="view_full_description">view full description</span>');
    	
    	
    	//var text = $(this).html();
  
		//if (text.length > len) {

        //    text = text.substring(0, len);
        //    text = text.replace(/\w+$/, '');
		//    text = text+'... <br><span class="view_full_description">view full description</span>';
		    
		//}
		
		//$(this).html('<div class="trunc">'+text+'</div>');
    	
    });
    
    $('.app_store_button').bind('click',function(){
       if(this.id=='android_app_locked'){
       	
    	if(client.isAndroid()){
			
			 window.open(social.android_market_bonus,'_blank');
			 
		   }else{
			 window.open(social.android_bitly,'_blank');
			}
       }
       
       if(this.id=='iphone_app_locked'){
    	//357
			 window.open(social.iphone_bitly,'_blank'); 
       
       }
       
    	
    });
    
    
    
    function hideURLbar(){
		window.scrollTo(0,1);
		}

	
	
	

    	$('.view_full_description').bind('click',function(){
		
			$(this).parents('.item').addClass('expanded_description');
		
		});
 
    if(mobile) {
    	 window.scrollTo(0,1);
    	
    	 if($('.landing_page').length==0){
    	 	
    	 	   $('.item').each(function(){
    	 	    
                    var item=$(this);
    	 	  		item.bind('click',function(){
    	 	  			
                        var permalink=item.find('.title a')[0].href;
                        window.location=permalink;

                   });
    	 	    	
			   });	
   		}
	
    }
    
	}
	
	this.resetPlayers = function(){
	     //return;
		 //stop players remove listeners and destroy doms... 
		 now_playing = {};
		 
		 $('*').removeClass('resume');
		 $('*').removeClass('pause_state');
		 
		 //$('#jquery_jplayer').jPlayer( "destroy" );
		 
		 //$('#jquery_jplayer').jPlayer('stop');
		 //$('audio').empty();
		 $('video').empty();
		// $('#jquery_jplayer').empty();
		
		 $('.player').empty();
		 $('.player').remove();
		 
		 //clean template only
		 $('.web_play_button').removeClass('pause_state');
		 
		 $('.web_play_button').show();
		 $('.item').removeClass('active_item');
		 global_lp=0;
		
    }

}

/*create item posts*/

function Post (config) {
	
	this.init = function () {
		  
		$('.web_play_button').each(function(){
			
			
			
			var params = $(this).parents('.item').data();
		
			$(this).parents('.item').addClass('item_'+params.file_class);
			$(this).bind('click',function(){
				
			  if($(this).parents('.item').hasClass('locked')){
				$(this).parents('.item').addClass('expanded');
				return;
			  }	
				  
			  if(params.file_class=='video'){
			  	
					  	  podcastpage.resetPlayers();
					  	  
					  	         $('#player_holder_'+params.item_id).css({height:370});
					  	         $('#web_play_button_'+params.item_id).hide();
					  	        	player= new Player(params);
					  	            player.autoplay = true;
					  	            player.render();
			  }else{
				
				
					  if($(this).hasClass('pause_state')){

					  	$("#jquery_jplayer").jPlayer("pause");
					  	$(this).removeClass('pause_state');
					  	$(this).addClass('resume');
					  	
					  }else if($(this).hasClass('resume')){

					  	$("#jquery_jplayer").jPlayer("play");
					  	$(this).removeClass('resume');
					  	$(this).addClass('pause_state');
					  	
					  }
					  
					  if(!$(this).hasClass('pause_state') && !$(this).hasClass('resume')){
						
					  	podcastpage.resetPlayers();
						player = new Player(params);
						player.autoplay=true;
						player.render();
						$('#jquery_jplayer').jPlayer("play");
					    player.poll();
						$(this).addClass('pause_state');
						
					  }
			  }
			});
			
			$(this).addClass(params.file_class);
			
			if(params.file_class == 'audio') {
	
				$(this).append('<div class="web_button_image"></div><span class="play_button_text">play</span>');
			}
			
			if(params.file_class == 'video'){
			
				
				$(this).before('<div style="background-image:url('+params.image+'/height/342);" id="animation_'+this.item_id+'" class="animation"></div>');
				$(this).css({'background-image':'url('+params.image+'/height/87'+')'});
				$(this).append('<div class="web_button_image"></div>');
				
			}

		});
		
		
			$('.description').each(function(){

		
		var clean = $(this).html();
		
		var full = '<div class="full">'+clean+'</div>';

		
		
		$(this).html(full);
	
		
		
	});
		
	}
	
	
	
	
}


/*player*/


function Player (config) {
	
	
	this.url = config.url;
	this.ext = this.url.substr( (this.url.lastIndexOf('.') +1) );
	
	this.default_mime_type = mime_library[this.ext].codec;
	

	this.mediaclass = (config.file_class) ? config.file_class : mime_library[this.ext].media;
	this.mime = (config.mime_type) ? config.mime_type : this.default_mime_type;
	this.id = config.item_id;
	this.autoplay = config.autoplay;
	this.image = config.image;
	
	this.state = 'playing'
	
	this.video_width = (config.video_width) ? config.video_width : 610;
	this.video_height = (config.video_height) ? config.video_height : 342;
	
	this.audio_width = (config.audio_width) ? config.audio_width : 295;
	this.audio_height = (config.audio_height) ? config.audio_height : 60;
	
	this.width = ((this.mediaclass == 'video') ? this.video_width : this.audio_height);
    this.height = ((this.mediaclass == 'video') ? this.video_height : this.audio_width);
    
    
	//podcastpage.resetPlayers();
	
	this.play = function (){
		
		$('#item_'+this.id).addClass('active_item');
		
	}
	
	this.pause = function () {
		
	}
	
	//decide which player to use
	this.render = function (){
		
		if(!this.mediaclass)return;
		
		
		if(mobile && (!client.isIphone())){
			$('.web_play_button').hide();
			$('#player_holder_'+this.id).append('<a href="'+this.url+'"  class="droid_play">PLAY</a>');
			$('.player_holder').css('margin-left',0);
			
			return;
		}
		
		
		$('#player_holder_'+this.id).append('<div id="player_'+this.id+'" class="video-js-box vim-css player '+this.mediaclass+'_player"></div>');
    
    	
    	
				        if(this.mediaclass=='audio'){
				            	this.jplayer();
				        }
				        
				        if(this.mediaclass=='video'){
				        	
                          
				           if(document.createElement(this.mediaclass).canPlayType) {
								        if (!document.createElement(this.mediaclass).canPlayType(this.mime)) {
									        this.wizzardplayer();
								        } else {
								        	//this.jplayer();
								        	
									        this.videojs();
								        } 
					       }else{
					            		this.wizzardplayer();
					            		
					       }
						}
						
					    $('.player').addClass(this.mediaclass+'_player');
	}
	
	this.wizzardplayer = function () {
	

		
		swfobject.embedSWF(
	            			'http://player.wizzard.tv/player/o/s'
	            			, 'player_'+this.id
	            			, this.width 
	            			, this.height
	            			, "9.0.0"
	            			, false
	            			, {
	                			'url': this.url
	                            ,'autoplay':false
	             			});
	}
	
	this.jplayer = function () {
		
		if(this.mediaclass=='audio') { var mediastring = {'mp3':player.url}; var supplied = 'mp3'}
		if(this.mediaclass=='video') { var mediastring = {'m4v':player.url}; var supplied = 'm4v'}
		
		$('#jquery_jplayer').jPlayer('setMedia',mediastring);
		                                  
									       if(this.autoplay){
									       	  	$('#jquery_jplayer').jPlayer("play");
									            player.poll();

									       }
					    
				 
					  
				var controls='<div id="player_container">'
				+'<div id="rewind"></div>'
				+'<div id="bars_holder">'
					+'<div class="xui-corner-all" id="sliderPlayback">'
						    +'<div style="background-color:#eee;height:14px;" id="loaded" class=""></div>'
					+'</div>'
				+'</div>'
				+'<div id="jplayer_play_time" class="jp_play_time time"></div>'
		        +'<div id="jplayer_total_time" class="jp_total_time time"></div>'	
				+'</div>';
		
	           $('.player').append(controls);
	           
	           $('#rewind').bind('click',function(){
	           	
	           	   var current_time= $("#jquery_jplayer").data("jPlayer").status.currentTime
	           	   var new_time = (current_time-30>0 ? current_time-30 : 0);
	           	   
	           	   if($("#jquery_jplayer").data("jPlayer").status.paused){
	           	   
	           	          $('#jquery_jplayer').jPlayer("pause",new_time);
	           	   }else{
	           	   	       $('#jquery_jplayer').jPlayer("play",new_time);
	           	   } 
	           	
	           });
				
	           var jpPlayTime = $("#jplayer_play_time");
	           var jpTotalTime = $("#jplayer_total_time");
               
	           //jpPlayTime.text('Loading...')
	           jpPlayTime.text('0:00');
	    
	           
	           var readable_time = $('#item_'+this.id).data('duration');
	           
	           if(readable_time){
	           	
	           this.duration = readable_time;
	           
	           jpTotalTime.text(readableTime(readable_time));
	           }
	           
				var current_pt=0;
				
			
				function showPauseBtn()
				{
					$("#play").hide()
				    $("#pause").show();
					
				}

				function showPlayBtn()
				{
					$("#pause").hide();
					$("#play").show();
					
				}
			
				if(this.autoplay){
					showPauseBtn();
				}else{
					showPlayBtn();
				}
	
				var pollcount=0;
				
	
				$("#play").click(function() {
					$("#jquery_jplayer").jPlayer("play");
					showPauseBtn();
					player.poll();
					return false;
				});
				
				
			
				$("#pause").click(function() {
					$("#jquery_jplayer").jPlayer("pause");
					showPlayBtn();
					return false;
				});
			
				// Slider
				$('#sliderPlayback').slider({
					max: 100,
					range: 'min',
					animate: true,
			
					slide: function(event, ui) {
						
					  if(ui.value* (100/global_lp)   < 100){
					  
					  
						$("#jquery_jplayer").jPlayer("playHead", ui.value*(100.0/global_lp));
					  }
						
						showPauseBtn();
					}
				});

			
				$('#dialog_link, ul#icons li').hover(
					function() { $(this).addClass('ui-state-hover'); },
					function() { $(this).removeClass('ui-state-hover'); }
				);
				
				
				
		

	}
	
	this.videojs = function() {
		
		 var html5tag;
		 var autoplay_tag = (this.autoplay)?' autoplay ':'';
		 
		 html5tag='<video class="video-js vim-css" poster="'+this.image+'/height/'+this.height+'" height="'+this.height+'" width="'+((client.isPad())?500: this.width)+'" class="video-js"  controls="true" '+autoplay_tag+'>'
			+'<source src="'+this.url+'" type="'+this.mime+'">'
			+'</video>';
		
		 $('#player_'+this.id).append(html5tag);
            
            
		 VideoJS.setupAllWhenReady();
		
	}
	
	this.poll = function () {
	
						var jpPlayTime = $("#jplayer_play_time");
						var jpTotalTime = $("#jplayer_total_time");
						
						
						
						var pollcount=0;
	
						//$('#jquery_jplayer').jPlayer("onProgressChange", function(lp,ppr,ppa,pt,tt) {
                        
						$('#jquery_jplayer').bind('jPlayer_timeupdate',function(e) {
						/*	
loadPercent Number (0 to 100) defining the percentage downloaded
playedPercentRelative Number (0 to 100) defining the percentage played when compared to the percentage downloaded.
playedPercentAbsolute Number (0 to 100) defining the the current play position in percentage
playedTimeNumber defining the current play position in milliseconds
totalTime  Number defining the total play time of the MP3 in milliseconds	
				*/			
							
							
		/*					
currentPercentAbsolute: 0.44620259130962026
currentPercentRelative: 1.2901389997336727
currentTime: 10.505000114440918
duration: 2354.311767578125
*/
		
		    if(!this.duration){
		    	var readable_time = parseInt(e.jPlayer.status.duration);
		    	
		    	
	           jpTotalTime.text(readableTime(readable_time));
		    }
		   
		    var lp = e.jPlayer.status.seekPercent;
		  
		    
		    
		    //console.log(e.jPlayer.status);
							    var ppa = e.jPlayer.status.currentPercentAbsolute;
							     var ppr = e.jPlayer.status.currentPercentRelative;
							      var pt = e.jPlayer.status.currentTime
							      
							      var loadpercent = e.jPlayer.status.loadPercent;
							      
							      var seekpercent = e.jPlayer.status.seekPercent;
							        $('#loaded').css('width',seekpercent+'%');
							     
								//workaround for edge bug not sure if we should do this or not...
								pollcount++;
								//$('#pollcount').html(pollcount);
						
								
								var lpInt = parseInt(lp);
								
								ppaInt = parseInt(ppa);
								
								if(ppr==0){
									jpPlayTime.text('loading');	
									$('.ui-slider').addClass('is_loading');
									$('#web_play_button_'+player.id).addClass('is_loading');
								}else{
									current_pt=0;
									jpPlayTime.text(readableTime(pt));
									$('.ui-slider').removeClass('is_loading');
									$('.web_play_button').removeClass('is_loading');
								}
					 		     global_lp = lpInt;
					
					 		$('#sliderPlayback').slider('option', 'value', ppaInt);
						}); 					
	}
}


/*actions for top menu buttons*/

function MenuButton(config){
		
		this.id = config.id;
		

		
		if(this.id=='iphone_app'){
			
			 window.open(social.iphone_app,'_blank');
		}
		
		if(this.id=='android_app'){
			
			 if(client.isAndroid()){
			
			 window.open(social.android_market,'_blank');
			 
			 }else{
			 window.open(social.android_app,'_blank');
			 }
		}
		
		if(this.id=='rss'){
			
			window.open(social.rss,'_blank');
			
		}
		
		if(this.id=='itunes'){
			
			window.open(social.itunes,'itunes_store');
		//<a href="http://itunes.apple.com/us/podcast/wtf-with-marc-maron-podcast/id329875043?uo=4" target="itunes_store">WTF with Marc Maron Podcast</a>
		}
		
		if(this.id=='info'){
			var modal = new modalWindow({
				windowId:'about_modal'
				,content: '<div class="modal_heading">'+$('#show_title').text()+'</div>'+$('.show_description').text()
				,eggTooth:'info'
				,width:((mobile) ? 280 :465)
				,height:300});
				
				modal.open();
		}
		
		if(this.id=='search'){
		
		  	
		 //$('#searchbox').remove();
			
		  var modal = new modalWindow({
		  	windowId:'search_modal',
		  	content:'<div id="searchbox_modal"><input id="modal_search_input" class="searchbox"><div id="modal_search_button" class="search_button link">Search</div></div>',
		  	eggTooth:'search',
		  	alignTo:'search',
	        width:(mobile) ? 280 :465,
	        height:300
		  }).open();
		  
		  
		 
	
		}
		
		if(this.id=='facebook'){
			
			
		 var facebook_modal_width = (mobile) ? 280 : 460
		 //http://www.facebook.com/pages/Marc-Maron/159240067038
		 var content='<iframe src="http://www.facebook.com/plugins/likebox.php?href=' + encodeURIComponent(social.facebook) + '&amp;width='+facebook_modal_width+'&amp;connections=16&amp;stream=false&amp;header=true&amp;height=287" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:'+facebook_modal_width+'px; height:287px;" allowTransparency="true"></iframe>';
		  
		  var modal = new modalWindow({
		  	windowId:'facebook_modal',
		  	//content:content,
		  	content:content,
		  	eggTooth:'facebook',
		  	width:facebook_modal_width,
		  	alignTo:'search',
	        height:275 
		  }).open();
		  
		}
		
		if(this.id=='twitter'){

		  var content='<div id="twitter_widget"></div>'; 
		  
		  var modal = new modalWindow({
		  	windowId:'twitter_modal',
		  	
		  	eggTooth:'twitter',
		  	content:content,
		  	alignTo:'search',
	        width:(mobile) ? 280 :600,
	        height:300
		  
		  }).open();
	
		  new TWTR.Widget({
							  version: 2,
							  id: 'twitter_widget',
							  type: 'profile',
							  rpp: 6,
							  interval: 6000,
							  width: (mobile) ? 280:500,
							  height: 300,
							  theme: {
							    shell: {
							      background: '#333333',
							      color: '#ffffff',
							      
							      background: '#ffffff',
							      color: '#333333'
							    },
							    tweets: {
							      background: '#000000',
							      color: '#ffffff',
							      links: '#00e1ff',
							      
							       background: '#7d7d7d',
							      color: '#ffffff',
							      links: '#00e1ff'
							    }
							  },
							  features: {
							    scrollbar: false,
							    loop: false,
							    live: false,
							    hashtags: true,
							    timestamp: true,
							    avatars: false,
							    behavior: 'all'
							  }
							}).render().setUser(social.twitter).start();
		}
		
		if(this.id=='email'){
			

		  window.location='mailto:'+social.email
		}
		     
		if(this.id=='phone'){
			
		  var content = '<a href="'+social.phone+'"><div class="action_button">'+social.phone+'</div></a>'
		
			
		  var modal = new modalWindow({
		  	windowId:'phone_modal',
		  	eggTooth:'phone',
		  	content:content,
		  	alignTo:'search',
	        width:(mobile) ? 280 :465,
	        height:300
		  
		  }).open();  
		}	
}


/*create modal window */

var modalWindow = function (params){
	
	  var win={
			parent:'body',
			eggTooth:params.eggTooth,
			windowId:params.windowId,
			content:params.content,
			width:params.width,
			height:params.height,
			close:function()
			{
				$(".modal-window").remove();
				$(".modal-overlay").remove();
			},
			open:function()
			{
				
				$('.modal-window').remove();
				$('.modal-window').empty();
				
				var social_positioning = $('#social_buttons').position().left;
				
				var icon_positioning = $('#'+this.eggTooth).position().left;
				
				
				var modal = "";
				
				modal += '<div class="modal-overlay"></div>';
				
				modal += "<div id=\"" + this.windowId + "\" class=\"modal-window\" style=\"width:" + this.width + "px; xheight:" + this.height + "px; xmargin-top:-" + (this.height / 2) + "px; xmargin-left:-" + (this.width / 2) + "px;\">";
				
				modal += this.content
				modal += "</div>";	
		
				$(this.parent).append(modal);
				
				
				$(".modal-window").append('<div class="eggtooth"></div>');
				
				$(".modal-window").append('<a class="close-window"></a>');
				
				$(".modal-window").css({left:social_positioning});
		        
				$(".eggtooth").css({left:icon_positioning-social_positioning});
		        
				
				
				$(".close-window").click(function(){win.close();});
				$(".modal-overlay").click(function(){win.close();});
			}
	  }
	  
	  return win;
};


/*detect client information*/

function Client() {
}

Client.prototype.padClients = [
    "pad"
]

Client.prototype.iphoneClients = [
    "iphone"
]

Client.prototype.failClients = [
    "droid"
]

Client.prototype.mobileClients = [
	"midp",
	"240x320",
	"blackberry",
	"netfront",
	"nokia",
	"panasonic",
	"portalmmm",
	"sharp",
	"sie-",
	"sonyericsson",
	"symbian",
	"windows ce",
	"benq",
	"mda",
	"mot-",
	"opera mini",
	"philips",
	"pocket pc",
	"sagem",
	"samsung",
	"sda",
	"sgh-",
	"vodafone",
	"xda",
	"iphone",
	"android"
];

Client.prototype.useragent = navigator.userAgent;

Client.prototype.isMobile = function()
{
	var agent = this.useragent.toLowerCase();

	for (var i in this.mobileClients) {
		if (agent.indexOf(this.mobileClients[i]) != -1) {
			return true;
		}
	}
	
	if(screen.width<600){
	   return true;	
	}
	
    return false;
}


Client.prototype.isIphone = function ()
{
	
	var agent = this.useragent.toLowerCase();
	
	
	
	for (var i in this.iphoneClients) {
		if (agent.indexOf(this.iphoneClients[i]) != -1) {
			return true;
		}
	}
    return false;
}

Client.prototype.isAndroid = function ()
{
	var agent = this.useragent.toLowerCase();
	for (var i in this.failClients) {
		if (agent.indexOf(this.failClients[i]) != -1) {
			return true;
		}
	}
    return false;
}

Client.prototype.isPad = function()
{
	var agent = this.useragent.toLowerCase();
	for (var i in this.padClients) {
		if (agent.indexOf(this.padClients[i]) != -1) {
			return true;
		}
	}
    return false;
}




$('document').ready(function(){
	    
	    client = new Client();
	    podcastpage = new Page();
	    post = new Post();
	    
		podcastpage.init();
		post.init();


		
		$('.social_button').live('click',function(e){ 
			 
			 var menubutton = new MenuButton({id:this.id});
			 e.stopPropagation();
		}); 
		
		if(mobile){
		addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false);

		function hideURLbar(){
		window.scrollTo(0,1);
		}
		}	
	if($('body').hasClass('premium')){
		if (client.isIphone() || client.isPad()){

     window.location=social.iphone_app;
     $('body').html('<font color="black">you are being redirected to the app store</font>');
     

		} 
		
		if (client.isAndroid()) {
		      window.location=social.android_market;
		     $('body').html('<font color="black">you are being redirected to the android market</font>');
		     
		}

	}
	
	

});



var mime_library ={ // Static Object
			mp3: {
				codec: 'audio/mpeg; codecs="mp3"',
				flashCanPlay: true,
				media: 'audio'
			},
			m4a: { // AAC / MP4
				codec: 'audio/mp4; codecs="mp4a.40.2"',
				flashCanPlay: true,
				media: 'audio'
			},
			oga: { // OGG
				codec: 'audio/ogg; codecs="vorbis"',
				flashCanPlay: false,
				media: 'audio'
			},
			wav: { // PCM
				codec: 'audio/wav; codecs="1"',
				flashCanPlay: false,
				media: 'audio'
			},
			webma: { // WEBM
				codec: 'audio/webm; codecs="vorbis"',
				flashCanPlay: false,
				media: 'audio'
			},
			m4v: { // H.264 / MP4
				codec: 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"',
				flashCanPlay: true,
				media: 'video'
			},
			ogv: { // OGG
				codec: 'video/ogg; codecs="theora, vorbis"',
				flashCanPlay: false,
				media: 'video'
			},
			webmv: { // WEBM
				codec: 'video/webm; codecs="vorbis, vp8"',
				flashCanPlay: false,
				media: 'video'
			}
		}
		
/*legacy js*/
function checkform ( form ) {
					if (form.comment_poster_email.value == "") {
						alert( "Please enter your email address." );
						form.comment_poster_email.focus();
						return false ;
					}
					if (form.comment_poster_name.value == "" ){
						alert( "Please enter your name." );
						form.comment_poster_name.focus();
						return false;
					}
					if (form.comment_body.value == "" ) {
						alert( "Please enter a comment.");
						form.comment_body.focus();
						return false;
					}

					return true ;
					}
					
					

function humane_date(date_str){
	var time_formats = [
		[60, 'Just Now'],
		[90, '1 Minute'], // 60*1.5
		[3600, 'Minutes', 60], // 60*60, 60
		[5400, '1 Hour'], // 60*60*1.5
		[86400, 'Hours', 3600], // 60*60*24, 60*60
		[129600, '1 Day'], // 60*60*24*1.5
		[604800, 'Days', 86400], // 60*60*24*7, 60*60*24
		[907200, '1 Week'], // 60*60*24*7*1.5
		[2628000, 'Weeks', 604800], // 60*60*24*(365/12), 60*60*24*7
		[3942000, '1 Month'], // 60*60*24*(365/12)*1.5
		[31536000, 'Months', 2628000], // 60*60*24*365, 60*60*24*(365/12)
		[47304000, '1 Year'], // 60*60*24*365*1.5
		[3153600000, 'Years', 31536000], // 60*60*24*365*100, 60*60*24*365
		[4730400000, '1 Century'], // 60*60*24*365*100*1.5
	];

	var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," "),
		dt = new Date,
		seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),
		token = ' Ago',
		i = 0,
		format;

	if (seconds < 0) {
		seconds = Math.abs(seconds);
		token = '';
	}

	while (format = time_formats[i++]) {
		if (seconds < format[0]) {
			if (format.length == 2) {
				return format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago
			} else {
				return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');
			}
		}
	}

	// overflow for centuries
	if(seconds > 4730400000)
		return Math.round(seconds / 4730400000) + ' Centuries' + token;

	return date_str;
};

if(typeof jQuery != 'undefined') {
	jQuery.fn.humane_dates = function(){
		return this.each(function(){
			var date = humane_date(this.title);
			if(date && jQuery(this).text() != date) // don't modify the dom if we don't have to
				jQuery(this).text(date);
		});
	};
}

function readableTime(readable_time) {
	
	readable_time=parseInt(readable_time);
	
	var detected_duration = parseInt(readable_time/60) + ':' + ( (readable_time % 60) < 10 ? "0" : "" ) +readable_time % 60;
	       
		    	var minutes = parseInt(readable_time/60);
	           
		    	minutes = (minutes>60) ?  (parseInt(minutes/60)+':'+( (minutes % 60) < 10 ? "0" : "" )+ minutes % 60):minutes
	            readable_time = minutes  + ':' + ( (readable_time % 60) < 10 ? "0" : "" ) +readable_time % 60;
		 return readable_time;   	
	
}
