/*
*************************************************

THOMSON REUTERS
JavaScript Functions

Created by the friendly folks at Happy Cog
http://www.happycog.com/

*************************************************
*/

// VARIABLES --------------------------------------------------


// browse tags
var BROWSE_COLUMNS = 4;
var COLUMN_DELIMITER = 8;
jQuery.noConflict();




// INITIAL ACTIONS --------------------------------------------------

function tr(){
	
	//home page
	createFlashStories();
	populateQuoteBox();
	roundTickerCorners();
	
	// Browse Products page
	initProductBrowse();
	
	// general functions
	greyInitialValues();
	initTabs();
	initLightbox();

}


jQuery(document).ready(function() { tr(); });







// FUNCTIONS --------------------------------------------------


/* =======================================
	Generic functions 
======================================= */

function greyInitialValues(){
	
	jQuery('input.filled').each(function(){
	
		this.startText = jQuery(this).attr('value');
	
	}).focus(function(){		
		
		if(jQuery(this).val() == this.startText){
			jQuery(this).val('');
			jQuery(this).removeClass('filled');	
		}
		
	}).blur(function(){
		
		if(jQuery(this).val() == ''){
			jQuery(this).val(this.startText);
			jQuery(this).addClass('filled');
		}
		
	});	
	
}


/* =======================================
	Tabs	
	http://docs.jquery.com/UI/Tabs
======================================= */

function initTabs(){
	var options = {expires: null, path: '/'};
   	var hashValue = window.location.hash.replace("#", "#tab_");
	if (window.location.pathname.indexOf("/news_ideas", 0) == 0) {
		if (hashValue == "") {
			var urlSections = document.referrer.split("/");
			var cookieValue = jQuery.cookie("nITab");
			if (urlSections.length > 4 && urlSections[3] == 'products_services')
				hashValue = '#tab_' + urlSections[4];
			if (hashValue == "" && cookieValue != null)
				hashValue = '#tab_' + cookieValue;
		}
		jQuery('div.searchcontainer').hide();
		jQuery('div.showtab').show();
		jQuery("nITab", null, options);
	}
	var hashValueExists = false;
	jQuery('.tabset .tabs li a').each(function(){
		if (jQuery(this).attr('href') == hashValue)
			hashValueExists = true;
	});
   	jQuery('.tabset').tabs({
    	select: function(event, ui) {
			window.location.hash = ui.tab.hash.replace("#tab_", "#");
   			if (window.location.pathname.indexOf("/news_ideas", 0) == 0) {
				jQuery('div.searchcontainer').hide();
				jQuery('div.showtab').show();
				jQuery.cookie("nITab", ui.tab.hash.replace("#tab_", ""), options);
   			}
		}});
	if (hashValueExists)
		jQuery('.tabset').tabs('select', hashValue);
}




/* =======================================
	Lightbox	
	http://leandrovieira.com/projects/jquery/lightbox/
======================================= */

function initLightbox(){ jQuery('.gallery a').lightBox(); }

function flashLightbox(containerId, count){
	var galleryName = "#" + containerId;	
	jQuery(galleryName).parent().find('a').eq(count).trigger('click');
}




/* =======================================
	Home page stories
======================================= */


/* Flash version */

function createFlashStories(){
	
	if(jQuery('.story').size() > 0){
		
		var numStories = jQuery('.story').size();
		
		jQuery('.story:eq(0)').parent().append('<div id="flash-stories"></div>');
		
		// flashvars
		var rawBackgrounds = new Array();
		var rawHeadlines = new Array();
		var rawBlurbs = new Array();
		
		jQuery('.story').each(function(n){
			var bg = jQuery(this).css("backgroundImage");
			bg = bg.replace("\"", "").replace("\"","");
			rawBackgrounds.push(bg);
    			if(n > 0){
        			rawHeadlines.push('breakerbreaker' + encodeURIComponent(jQuery(this).find('h2:eq(0)').text()));
        			rawBlurbs.push('breakerbreaker' + encodeURIComponent(jQuery(this).find('p:eq(0)').html()));
   			 }else{
        			rawHeadlines.push(encodeURIComponent(jQuery(this).find('h2:eq(0)').text()));
			        rawBlurbs.push(encodeURIComponent(jQuery(this).find('p:eq(0)').html()));
    			}
		});

		
		// Flash params	
		
		var flashvars = { 
			
			numStories: jQuery('.story').size(),
			rawBackgrounds: rawBackgrounds,
			rawHeadlines: rawHeadlines,
			rawBlurbs: rawBlurbs
			
		}
		
		swfobject.embedSWF("/now/swf/stories3.swf", "flash-stories", "920", "308", "9.0.0","/now/swf/expressInstall.swf", flashvars, { menu: 'false'}, {});
		
	}
	
}


/* =======================================
	Home page Reuters box
======================================= */

function populateQuoteBox(){
	
	jQuery('#reuters #quote').attr('value', jQuery('label[for="quote"]').html());
	jQuery('#reuters #quote').addClass('filled');
	jQuery('label[for="quote"]').remove();
	
}

function loadTicker(loc, el){
	
	jQuery('#ticker .toggle li.current').removeClass('current');
	el.parent().addClass('current');
	
	jQuery('#market-news').load(loc, function(){
		jQuery('#market-news table:eq(0)').hide();
		jQuery('#market-news table:eq(0)').fadeIn('normal');
	});	
	
	return false;
	
}

function roundTickerCorners(){
	
	jQuery('#reuters #ticker .toggle a').append('<b class="tl"></b><b class="tr"></b><b class="bl"></b><b class="br"></b>');
	jQuery('#selected_tags a').append('<b class="tl"></b><b class="tr"></b><b class="bl"></b><b class="br"></b>');
	
}



/* =======================================
	Browse Products by Tag
======================================= */

function initProductBrowse(){
	
	if(jQuery('#product_browse').size() > 0){
		
		jQuery('#product_browse #tag_chooser form label').each(function(){
		
			jQuery('#product_browse #tag_chooser').append('<div class="tag-section" id="' + jQuery(this).attr('for') + '"><h3 class="sIFR-ignore">' + jQuery(this).html() + '</h3><ul class="tags"></ul></div>');
			
			jQuery(this).next().children().each(function(m){					
							
				if(jQuery(this).children().size() > 0){ // if this is an <optgroup>				
					
					var kids = jQuery(this).children().size();
					
					// create label
					jQuery('#tag_chooser .tag-section:last-child ul.tags').append('<li class="nested"><span class="category">' + jQuery(this).attr('label') + '</span></li>');				
					
					
					// create new nested <ul> or <table>
					if(kids > COLUMN_DELIMITER){
						jQuery('#tag_chooser .tag-section:last-child ul.tags > li:last-child').append('<table><tr><td></td><td></td><td></td><td></td></tr></table>');
						
						var perColumn = Math.floor(kids/4);
						var overflowColumns = kids%4;
						var columnNums = [];
						var currentColumn = 0;
						var columnCounter = 0;
						
						for(var i = 0; i <= 3; i++){
							if(i < overflowColumns){
								columnNums.push(perColumn+1);
							}else{
								columnNums.push(perColumn);
							}							
						}					
						
						jQuery('.tags table').hide();						
						
					}else{
						jQuery('#tag_chooser .tag-section:last-child ul.tags > li:last-child').append('<ul></ul>');	
						jQuery('ul.tags ul').hide();					
					}			
					
					
					// populate new nested <ul> or <table>
					jQuery(this).children().each(function(n){
							
						if(kids > COLUMN_DELIMITER){
							if(columnCounter == columnNums[currentColumn]){
								currentColumn++;
								columnCounter = 1;
							}else{
								columnCounter++;
							}		
							
							if(jQuery(this).attr('selected')){
								jQuery('#tag_chooser .tag-section:last-child ul.tags > li:last-child > table td').eq(currentColumn).append('<a class="selected" href="#">' + jQuery(this).html() + '</a>');
							}else{
								jQuery('#tag_chooser .tag-section:last-child ul.tags > li:last-child > table td').eq(currentColumn).append('<a href="#">' + jQuery(this).html() + '</a>');								
							}							
							
						}else{
							if(jQuery(this).attr('selected')){
								jQuery('#tag_chooser .tag-section:last-child ul.tags > li:last-child > ul:eq(0)').append('<li><a class="selected" href="#">' + jQuery(this).html() + '</a></li>');
							}else{
								jQuery('#tag_chooser .tag-section:last-child ul.tags > li:last-child > ul:eq(0)').append('<li><a href="#">' + jQuery(this).html() + '</a></li>');
							}
						}							

					});
					
				}else{ // if this is an <option>
					
					jQuery('#tag_chooser .tag-section:last-child ul.tags').addClass('one_level');
					
					if(jQuery(this).parent().children().size() > COLUMN_DELIMITER){	
						if(jQuery(this).attr('selected')){
							jQuery('#tag_chooser .tag-section:last-child ul.tags').append('<li class="column' + Math.floor(m/BROWSE_COLUMNS) + '"><a class="selected" href="#">' + jQuery(this).html() + '</a></li>');
						}else{
							jQuery('#tag_chooser .tag-section:last-child ul.tags').append('<li class="column' + Math.floor(m/BROWSE_COLUMNS) + '"><a href="#">' + jQuery(this).html() + '</a></li>');
						}					
						
					}else{
						jQuery('#tag_chooser .tag-section:last-child ul.tags').append('<li><a href="#">' + jQuery(this).html() + '</a></li>');
					}
				}
				
			});		
		
		});	
		
		//label handler
		jQuery('span.category').mouseenter(function(){
			if(jQuery(this).next().is(':hidden')){	
				jQuery(this).removeClass('category').addClass('category-over');
			}else{
				jQuery(this).removeClass('category-collapse').addClass('category-collapse-over');
			}						
		}).mouseleave(function(){
			if(jQuery(this).next().is(':hidden')){
				jQuery(this).removeClass('category-over').addClass('category');
			}else{
				jQuery(this).removeClass('category-collapse-over').addClass('category-collapse');
			}
		}).click(function(){
			if(jQuery(this).next().is(':hidden')){
				jQuery(this).removeClass('category category-over').addClass('category-collapse-over');
				jQuery(this).next().show();
			}else{
				jQuery(this).removeClass('category-collapse category-collapse-over').addClass('category-over');
				jQuery(this).next().hide();
			}
		});
		
		
		
	
		jQuery('#product_browse #tag_chooser form').hide();
		
		// h3 handler
		jQuery('.tag-section h3').mouseenter(function(){
			jQuery(this).addClass('over');
		}).mouseleave(function(){
			jQuery(this).removeClass('over');
		}).click(function(){
			
			// highlight section
			if(jQuery(this).hasClass('current')){
				jQuery(this).removeClass('current').addClass('over');
			}else{
				jQuery(this).removeClass('over').addClass('current');
			}
			
			// open/close tags			
			if(jQuery(this).next().css('left') == '-9999px'){
				jQuery(this).next().css({'left': '0'});
				jQuery(this).next().hide();
				jQuery(this).next().slideDown('normal');
			}else{
				jQuery(this).next().slideUp('fast', function(){
					jQuery(this).css({'left': '-9999px'});
				});
				
			}
		});
	
	}
	
}

/* =======================================
Hidden Div
======================================= */

function reveal(divId, linkId) {
	//Reveal the div
    e = document.getElementById(divId);
    if (e) {
        e.style.display = "block";
    } else {
        alert("Error: Could not locate element with id: " + e);
    }
    //Remove the link
    e = document.getElementById(linkId);
    if (e) {
        e.style.display = "none";
    } else {
        alert("Error: Could not locate element with id: " + e);
    }
}

