// *****************************************************************************

/* footer sitemap */	
function footernav_init() {
		//var dd = document.domain;
		var fnav = jQuery("div#footernav div#fnav");
		fnav.load("/static/footer.html");		
 		
 		var expander = jQuery("div#footernav a.expander");
 		expander.click(
			function() {
				fnav.toggle();				
				return false;
			}
		);
		expander.toggle(
      				function () {
        				jQuery(this).css({"backgroundPosition":"bottom right"});
        				jQuery("#footernav").css({"marginBottom":"525px"});
      				},
      				function () {
        				jQuery(this).css({"backgroundPosition":"top right"});
        				jQuery("#footernav").css({"marginBottom":"0"});
      				}
    			);
	
}
function gateway_init() {
        /* Check whether the browser is IE. If so, flashVideoPlayer is
        window.videoPlayer. Otherwise, it's document.videoPlayer. The
        videoPlayer is the ID assigned to the <object> and <embed> tags. */
        var isIE = navigator.appName.indexOf("Microsoft") != -1;
        flash_player = (isIE) ? window['flash_player1'] : document['flash_player1'];
}

/* clear input field  */	
function doClear(theText) {
     if (theText.value == theText.defaultValue) {theText.value = "";}
}
/*
 * clear and restore input field
 * Usage: Put the following line in jQuery(document).ready: 
 * 		jQuery(".ClassNameOfClearableFields").doClear2();
 */ 
jQuery.fn.doClear2 = function() {
	return this.focus(function() {
		if( this.value == this.defaultValue ) {
			this.value = "";
		}
	}).blur(function() {
		if( !this.value.length ) {
			this.value = this.defaultValue;
		}
	});
};
 
/* get today's date */	
function todaystring() {	
	var today = new Date();
	var day = '';
	switch (today.getDay()) {
    case 0:
      day = 'Sunday'; break;
    case 1:
      day = 'Monday'; break;
    case 2:
      day = 'Tuesday'; break;
    case 3:
      day = 'Wednesday'; break;
    case 4:
      day = 'Thursday'; break;
    case 5:
      day = 'Friday'; break;
    case 6:
      day = 'Saturday'; break;
  }
	var mo = today.getMonth()+1;
	mo = (mo < 10) ? '0'+mo : mo;
	var daydigit = today.getDate();
	daydigit = (daydigit < 10) ? '0'+daydigit : daydigit;
	var year = today.getFullYear();
	year = (year+"").substring(2,4);
	return day+', '+mo+'.'+daydigit+'.'+year;
}
/* load file */
function loadFile(id, file){
	jQuery('div#'+id).load(file);
}

/* load grid pane on bloggers and columnists with sort options */	
function loadGridPane_sort(file) {
	jQuery('div#grid div.latest').load(file+'.html');	
	//setTimeout("reinitialiseScrollPane();", 200);
	jQuery('div#grid div.alpha').load(file+'_alpha.html');
}

/* load grid pane */
function loadGridPane(file) {
	jQuery('div#grid').load(file);	
	//setTimeout("reinitialiseScrollPane();", 200);
}
function reinitialiseScrollPane(){
	jQuery('#grid').jScrollPane({showArrows:true, scrollbarWidth: 16, scrollbarMargin: 0, arrowSize: 24, dragMinHeight:88});
}

/* load community panel */	
function loadCommunity(section, obj) {
	jQuery('p#newsfrom_bcounty').remove();
	jQuery('li.load_msg').show();
	jQuery('div#community_template').load('/'+section+'/v-community/index.html', function(){
			jQuery('li.load_msg').hide();
			if (section == 467){drawNewsFrom(obj);}
		});
	return false;
}
function drawNewsFrom(obj){
	var aText = jQuery(obj).text();
	var newsFrom = '<p id="newsfrom_bcounty" class="newsfrom" style="float: none;"><span>NEWS FROM:</span> Broward County and '+aText+'</p>';
	jQuery('div#community_template').prepend(newsFrom);
}

jQuery(document).ready(function() { 
	window.setTimeout("footernav_init();", 500); 
	
/* panel nav - change background image to highlighted */		
	var navLink = jQuery("div.panelnav ul:not(.link-list) li:not(.sort) a, div.tab div.subnav ul li a, div.subnav_bottom ul li a");
 		navLink.click(
			function() {
				jQuery(this).parent("li").siblings().removeClass("x");				
				jQuery(this).parent("li").addClass("x");				
				return false;
			}
		);
		
/* initialize news grid */	
	jQuery("ul.newsgrid li:eq(1)").addClass("x");
	jQuery("div#newsgrid span.newsgrid").children("div.topStories:first").show();

/* define newsgrid tab clicks */
	jQuery('a.newsgridTab').click(
			function() {
                var tabID = jQuery(this).attr('id');
                tabID = tabID.replace('tab_','');
				jQuery('#newsgrid span.newsgrid').children('div.topStories').hide();
                jQuery('div.'+tabID).show();
                return false;
			}
		);

/* calculate timestamps for mainstage stories */
	var timestamps = jQuery('span.timestamp');
	jQuery.each(timestamps, function(){
		var current_time = Math.round(new Date().getTime()/1000.0);
		var modified_time = parseInt(jQuery(this).text(),10); //strip non numbers
		var time_diff = current_time - modified_time; 
		var timestamp = new Date(modified_time * 1000);
		var hrs = timestamp.getHours();		
		var ampm = (hrs < 12) ? ' AM ' : ' PM ';
		hrs = (hrs > 12) ? hrs - 12 : hrs;
		var mins = timestamp.getMinutes();
		mins = (mins < 10) ? '0'+mins : mins;		
		var mins_ago = new Date((current_time - modified_time) * 1000);
		mins_ago = mins_ago.getMinutes();
		mins_ago = (mins_ago == 0) ? 1 : mins_ago;
		var min_string = (mins_ago == 1) ? ' minute ago' : ' minutes ago';
		if (time_diff < 3300){
			timestamp = 'Updated '+mins_ago+ min_string;
		} else {		
			timestamp = hrs+':'+mins+ampm+' ET';
		}
		jQuery(this).text('- '+timestamp);
		jQuery(this).show();
	});	

/* scroll left and right functionality for inside miamiherald panels */
	jQuery.scrollTo.defaults.axis = 'x';
	jQuery('div.scroll').scrollTo( 0 );//reset all scrollable panes to (0,0)
	jQuery.scrollTo( 0 );//reset the screen to (0,0)
	var paneTarget = jQuery('div.scroll');	
	jQuery('img.right').click(function(){
				jQuery(this).nextAll(paneTarget).stop().scrollTo( '+=264px', 800 );
			});
	jQuery('img.left').click(function(){
				jQuery(this).nextAll(paneTarget).stop().scrollTo( '-=264px', 800 );
			});
			
/* tabs - change background image to highlighted */	
	jQuery('ul.tabs li a').click(
			function() {
				jQuery(this).parent("li").siblings().removeClass("x");				
				jQuery(this).parent("li").addClass("x");				
				return false;
			}
		);		
		
/* sort functionality for columnists and bloggers pages */
	jQuery('a#alpha').click(
			function() {
				jQuery('div.panelnav ul li.sort a').removeClass("x");				
				jQuery(this).addClass("x");			
				jQuery('div.latest').hide();						
				jQuery('div.alpha').show();		
				return false;
			}
		);
	jQuery('a#latest').click(
			function() {
				jQuery('div.panelnav ul li.sort a').removeClass("x");				
				jQuery(this).addClass("x");			
				jQuery('div.alpha').hide();						
				jQuery('div.latest').show();		
				return false;
			}
		);
		
/* set the highlighted background image for the first and last navbar items w rounded corner images */
	if (jQuery('#navbar ul li.f').children('a').hasClass('x')){
		jQuery('#navbar ul li.f').css({ backgroundPosition:'-26px 100%'});
	}
	if (jQuery('#navbar ul li.l').children('a').hasClass('x')){
		jQuery('#navbar').css({ backgroundPosition:'976px 100%'});
	}
	jQuery('#navbar ul li.f a').hover(
		function() {jQuery('#navbar ul li.f').css({ backgroundPosition:'-26px 100%'});},
		function() {
			if (jQuery(this).hasClass('x')){	return false;}
			else{jQuery('#navbar ul li.f').css({ backgroundPosition:'-26px 0'});	}
		});
	jQuery('#navbar ul li.l a').hover(
		function() {jQuery('#navbar').css({ backgroundPosition:'976px 100%'});},
		function() {
			if (jQuery(this).hasClass('x')){return false;}
			else{jQuery('#navbar').css({ backgroundPosition:'976px 0'});	}
		});
	jQuery('ul.newsgrid li:last').addClass('end');	
	jQuery('a.external').append('&nbsp;<img src="/images/redesign/icons/external.gif" />');	
	
/* add Next button to comments */
	window.setTimeout("addPagerLinks();", 3000);      

});	

/*********************
 * Use this to parse a query string
 * If only a single argument is passed, the browsers URL will be used for the query
 * If both arguments are passed, the first will be searched for in the second
 */ 
function getQueryStrVariable(variable,hrefstring) { 
	if (!(hrefstring)) {
		var hrefstring = window.location.href;
	}
	var queryIndex = hrefstring.indexOf('?') + 1; 
	var query = hrefstring.substring(queryIndex); 
	var vars = query.split("&"); 
	for (var i=0;i<vars.length;i++) { 
		var pair = vars[i].split("="); 
		if (pair[0] == variable) { 
			return pair[1]; 
		} 
	} 
	return false;
} // END getQueryString()

// *****************************************************************************
function addPagerLinks() {
	var pageNum = parseInt(jQuery('div#nyxComments_pager span.paginationNavLinks span').text());
	pageNext = pageNum + 1;
	var pageUrl = location.href;
	pageUrl = pageUrl.substring(0,pageUrl.lastIndexOf("\?"));
	var nextUrl = pageUrl+'?pageNum=' + pageNext + '&mi_pluck_action=page_nav#Comments_Container';
	var nextLink = '<a class="pager" href="'+nextUrl+'">Next</a>';	
	jQuery('div#nyxComments_pager span.paginationNavLinks a:last-child').after(' '+nextLink);
	if (pageNum > 1) {		
		pagePrev = pageNum - 1;
		var prevUrl = pageUrl+'?pageNum=' + pagePrev + '&mi_pluck_action=page_nav#Comments_Container';
		var prevLink = '<a class="pager" href="'+prevUrl+'">Prev</a>';
		jQuery('div#nyxComments_pager span.paginationNavLinks a:first-child').before(' '+prevLink+' ');
	}
}
/*********************
 * Test Alert functionality. 
 * In storylevel, add ?test=1 to URL to enable debug mode
 */
function alertTest2(alertTestMessage) {
// Use this to activate or deactivate the level 2 alert messages
	if (getQueryStrVariable('test') == '2') {
		alert(alertTestMessage);
	}
}
function alertTest(alertTestMessage) {
// Use this to activate or deactivate the level 1 alert messages
	if (getQueryStrVariable('test') == '1') {
		alert(alertTestMessage);
	}
}
// *****************************************************************************

/**
 * jQuery functions to test if an element exists.
 * .ifExists() can be chained in a jQuery call and .exists() can be tested for true/false.
 *  example: if (jQuery(selector).exists()) { }
 */
jQuery.fn.exists = function() { return (this.length > 0); };
jQuery.fn.ifExists = function() { if (this.length > 0) { return this; } };

/**
 * Flash Gallery Filename and location provider
 * Use this to get the filename of the various flash photo galleries.
 * Increment the flash file name.
 * The server and browsers cache flash media so agressively that the best way to 
 * update it is to use a new filename. However, that would mean editing many 
 * PubSys files and updating the whole site.
 * This way is much faster and more reliable.
 * 
 * Returns URL of the flash gallery
 * Filenames should be in the form: filename-es-preview-v#.swf where v# is the number used to update te filename
 */
function getFlashGalleryURL(whichGallery, hideURL){
//	console.log("running flashGalleryURL for whichGallery = " + whichGallery);

  var langFileSuffix = "-es"; // default language suffix
	var previewSuffix = "-preview";
	var mediaSubDomain = "media";
	var flashGalleryURL = ""; // placeholder for final URL to be returned

	// Need to determine: which site, which gallery, preview version?
  var thisDomain = window.location.hostname;

  // SETUP PREVIEW
  var previewSuffix = "";
	var thisSubDomain = "www";
	if (thisDomain.indexOf("preview.") === 0){
		previewSuffix = "-preview";
		thisSubDomain = "preview";
    // Eventually, this may be able to override the media subdomain
    // once the flash galleries know how to use the preview domain to get the XML feed
    // See: /pubsys/production/section/gallery_stack.html
    mediaSubDomain = mediaSubDomain; 
	}

  // SETUP LANGUAGE
  // Get domain start position w/o subdomain. Assume miamiherald.com
	var thisDomainStartChar = thisDomain.indexOf('miamiherald.com');
  // If this turns out to be elNuevoherald.com
	if (thisDomainStartChar == -1) {
		thisDomainStartChar = thisDomain.indexOf('elnuevoherald.com');
    // Leave Language for ElNuevo
	}
	else {
    // Set language to default
    langFileSuffix = '';
	}

  // Set domain name
  thisDomain = thisDomain.substring(thisDomainStartChar);

  // Setup URL to be prepended to filename
  var thisChannelURL = "http://" + mediaSubDomain + "." + thisDomain + "/static/multimedia/channels/";
  var thisPanelURL = "http://" + mediaSubDomain + "." + thisDomain + "/static/multimedia/panels/";
  var thisStoryDetailURL = "http://" + mediaSubDomain + "." + thisDomain + "/static/multimedia/story_detail/";
  if (hideURL == true) {
    // allow the function to return only the filename in case it is needed in a special context
    // For example, the video section requires the url to be escaped
    thisChannelURL = "";
    thisPanelURL = "";
    thisStoryDetailURL = "";
  }
  var thisVersionSuffix = "";

 ///////////////////////////////////////////////////////////////////////////////////////////////////
 // UPDATE FILENAME VERSIONS HERE
 ///////////////////////////////////////////////////////////////////////////////////////////////////
	switch(whichGallery) {
		// NOTE: If a file does not use Language or preview versions, empty the var here
		// CHANNEL
		case "SectionFrontPhotoGallery":
			flashGalleryURL = thisChannelURL + "SectionFrontPhotoGallery";
			thisVersionSuffix = (langFileSuffix == "") ? "-v7a" : "-v7a"; // English : Spanish
			break;
    case "VideoPlayer-SectionFront":
      flashGalleryURL = thisChannelURL + "VideoPlayer-SectionFront";
      thisVersionSuffix = (langFileSuffix == "") ? "-v2" : "-v2a"; // English : Spanish
      break;
		// PANELS
    case "MultimediaPanel-PhotoGallery":
      flashGalleryURL = thisPanelURL + "MiamiHerald-MultimediaPanel-PhotoGallery";
      thisVersionSuffix = (langFileSuffix == "") ? "-v8a" : "-v8a"; // English : Spanish
      break;
    case "MultimediaPanel-VideoPlayer":
      flashGalleryURL = thisPanelURL + "MiamiHerald-MultimediaPanel-VideoPlayer";
      thisVersionSuffix = (langFileSuffix == "") ? "-v3" : "-v3"; // English : Spanish
      break;
    case "CommNewsUserPhotosSectionFront-PhotoGallery":
      flashGalleryURL = thisPanelURL + "CommNews-MultimediaPanel-PhotoGallery";
      langFileSuffix = ""; // No spanish version of cummunity news
      thisVersionSuffix = (langFileSuffix == "") ? "-v7a" : "-v7a"; // English : Spanish
      break;
		// STORY DETAIL
    case "StoryLevel-VideoPromo":
      flashGalleryURL = thisStoryDetailURL + "MiamiHerald-StoryLevel-VideoPromo";
      thisVersionSuffix = "";
      langFileSuffix = "";
      break;
    case "StoryLevel-PhotoGallery":
      flashGalleryURL = thisStoryDetailURL + "StoryLevel-PhotoGallery";
      thisVersionSuffix = (langFileSuffix == "") ? "-v8m" : "-v8m"; // English : Spanish
      break;
    case "UnifiedVideoPlayer":
      flashGalleryURL = thisStoryDetailURL + "UnifiedVideoPlayer";
      thisVersionSuffix = "";
			langFileSuffix = "";
      break;
	  }
	
	return flashGalleryURL + langFileSuffix + previewSuffix + thisVersionSuffix + ".swf";
	
/*

PubSys Files calling this
 * /pubsys/production/section/gallery_content.html
 * /pubsys/production/section/gallery_detail_content.html
 * /pubsys/production/section/multimedia_panel_photo_gallery.html
 * /pubsys/production/section/multimedia_panel_video_player.html
 * 
 * /pubsys/production/story/video_promo.html
 * 
 * /pubsys/production/section/digital_neighbors/dn_gallery_content.comp
 * 
 * Static Server: /static/scripts/redesign/story_detail.js
 * 
 * CHANNELS - /static/multimedia/channels
 * SectionFrontPhotoGallery.swf
 * SectionFrontPhotoGallery-es.swf
 * VideoPlayer-SectionFront.swf
 * VideoPlayer-SectionFront-es.swf
 *
 * PANELS - static/multimedia/panels
 * MiamiHerald-MultimediaPanel-PhotoGallery.swf
 * MiamiHerald-MultimediaPanel-PhotoGallery-es-preview.swf
 *
 * MiamiHerald-MultimediaPanel-VideoPlayer.swf
 *
 * STORY DETAIL - /static/multimedia/story_detail
 * MiamiHerald-StoryLevel-VideoPromo.swf
 * StoryLevel-PhotoGallery.swf
 * UnifiedVideoPlayer.swf
 *
 */

} // END getFlashGalleryURL()

/**
 * EMAIL THIS LINK
 * Display Email Form from the Flash player. Use this to pass return false; and to modify the URL as needed
 * to handle preview and add the URL version
 * @param {Object} url
 */
// 
function displayEmailForm_launcher(url) {
	var url_ = url;
	var email_url_version =  "v-emailform";
	// Check if preview
	if ((window.location.hostname).indexOf("preview.") === 0) {
    url_ = url_.replace("www.", "preview.");
  }
	// Add URL Version if needed
	// Should be in format http://www.miamiherald.com/2010/03/17/v-emailform/1533456/miami-dolphins-keep-guard-richie.html
	if (url_.indexOf(email_url_version) == -1) {
		// Split URL
		var urlAry = url_.split("/");
		// Get length of array
		var urlAryLen = urlAry.length;
		// Reset url placeholder
		url_ = "";
		// Write all URL array component fields except for last 2: section ID and filename
    for (var i=0; i<(urlAryLen-2); i++) {
      url_ += urlAry[i] + "/";
    };
		// Write URL version
      url_ += email_url_version + "/";
		// Write last 2 URL array component fields: section ID and filename
      url_ += urlAry[urlAryLen-2] + "/";
      url_ += urlAry[urlAryLen-1];
	}
	
  displayEmailForm(url_);
  return false;
} // END displayEmailForm_launcher()

// get comment pref cookie
	var cookies = document.cookie;
	var pos = cookies.indexOf('global_comment_pref=');
	if (pos != -1) {
		var start = pos + 20;
		var end = cookies.indexOf(";", start);
		if (end == -1) end = cookies.length;
			var comment_cookie = cookies.substring(start,end);
        } else if(pos == -1) {
            var mhcomcookie = '0';
        }
	if (comment_cookie == '1') {
            var mhcomcookie = '1';
        } else if (comment_cookie == '') {
            var mhcomcookie = '0';
        }
// START toggle comments
    
    $(document).ready(function(){
        
        // go ahead and set the expires date variable
        var date = new Date();
        date.setTime(date.getTime()+(365*24*60*60*1000));
        var expires = date.toGMTString();
        
        // if its show or null then set button and comment toggle class to hide
        if (mhcomcookie == '0') {
            $('#comment_toggle').attr('class', 'hide');
            $('#comment_toggle span.hide, div#guidelines-wrap, div#disclaimer-wrap, div#commentingStage').show();
        } else if ( mhcomcookie == '1') {
            $('#comment_toggle').attr('class', 'show');
            $('#comment_toggle span.show').show();
        }
        
        // upper comment pref confirm bubble function
        $('span#comment_pref a').click(function(){
            $('#comment_bubble_top').fadeIn();
        });
        
        // upper comment pref ok button click function
        $('#comment_bubble_up img.ok').click(function(){
            // cookie plugin to set cookie to show
            document.cookie = 'global_comment_pref=; expires='+expires+'; path=/; domain=.miamiherald.com';
			// reload current window
            window.location.reload();
            
        });
        
        // upper comment pref ok button click function
        $('#comment_bubble_top img.ok').click(function(){
            // cookie plugin to set cookie to show
            document.cookie = 'global_comment_pref=; expires='+expires+'; path=/; domain=.miamiherald.com';
			// reload current window
            window.location.reload();
            
        });
        
        // lower comment button confirm bubble function
        $('#comment_toggle').click(function(){
            $('#comment_bubble').fadeIn();
            
            if ($(this).attr('class') == 'hide') {
                $('#comment_bubble p').text('Comments will be hidden on all stories.');
            } else if ($(this).attr('class') == 'show') {
                $('#comment_bubble p').text('Comments will be displayed on all stories.');
            }
        });
        
        $('img.ok').click(function(){
            var state = $(this).parents('#comment_toggle').attr('class');
            if (state=='hide'){
                // use cookie plugin to create or set cookie to hide
                document.cookie = 'global_comment_pref=1; expires='+expires+'; path=/; domain=.miamiherald.com';
                // reload current window
                window.location.reload();            
            }
        
            // if state is show set cookie to show and reload page
            if (state=='show'){
                // cookie plugin to set cookie to show
                document.cookie = 'global_comment_pref=; expires='+expires+'; path=/; domain=.miamiherald.com';
				// reload current window
                window.location.reload();
            }
        });
        
        $('img.cancel').click(function(){
            $('#comment_bubble, #comment_bubble_up, #comment_bubble_top').fadeOut();
            return false;
        });
  
    });
// END toggle comments
