var createdBookmarkForm = null;

jQuery(document).ready(function()
{   
    try {
        if(jQuery("#insights_service_name").val() != "") {   
            jQuery("#insights_service_name").val("");
        }
        
    	renderBookmarkLinks();
    	processBookmarkLinks();	

    	if(jQuery.cookie("categoryCount") != null) {
        	doSearchFromServicesWapplet(jQuery.cookie("categoryCount"));
            jQuery.cookie("categoryCount", null);
         }
        
     } catch(error) {}
});	

/*
 * Removed per TFC's request for now - search string autocomplete
 * jQuery(document).ready(function() {
 * jQuery("#tfcSearchForm").find("#header_search_textbox_input").autocomplete("/?ct=searchsg", {
 * parse: function(data) { var parsed = [];
 * 
 * var thing = jQuery(data).find("#stRec").find("li").each(function() {
 * parsed[parsed.length] = { data: [jQuery(this).text()], value:
 * jQuery(this).text(), result: [jQuery(this).text()] }; });
 * 
 * return parsed; }, dataType: "text" }); });
 */
function destroyBookmarkForm() {
    try {
    	if(createdBookmarkForm != null ) {
    		createdBookmarkForm.detach();
    		createdBookmarkForm = null;
    	}
    } catch(error) {}
}

function toggleSearchTermPreloader(on) {
	if ( on )
		$.blockUI({ 
			message:'<img src="http://www.thefuturescompany.com/file_depot/0-10000000/0-10000/1/folder/55/waiting.gif">',
			css: {border: '0px',padding: '0px 0px',width: '64px',opacity: .75,top: '192px',left: ($(window).width() - 64) /2 + 'px'},
        	cursor: null,
		 	showOverlay: false
		 });
	else
		$.unblockUI();
}			

function renderBookmarkLinks(bookmark_entity_type) {
    try {
    	if(bookmark_entity_type) {
    		if(jQuery("div[id='bookmark_entity_type_"+bookmark_entity_type+"']").length == 0) {
    			var savedBookmark = bookmark_entity_type.substr(bookmark_entity_type.indexOf(":")+1);
	    	    jQuery("#article_container").find("div[name$='"+savedBookmark+"']").find("#search_result_related_bottom_box04>ul").removeClass("list_search_links_bookmarked").addClass("list_search_links").find("li").replaceWith('<li><div style="cursor: pointer;">Bookmark</div></li>');
	    	    jQuery("#highlight_article").find("div[name$='"+savedBookmark+"']").find("#search_result_related_bottom_box04>ul").removeClass("list_search_links_bookmarked").addClass("list_search_links").find("li").replaceWith('<li><div style="cursor: pointer;">Bookmark</div></li>');
	    	    jQuery("#latest_update_container").find("div[name$='"+savedBookmark+"']").find("#latestupdate_bookmark_links>ul").removeClass("list_search_links_bookmarked").addClass("list_search_links").find("li").replaceWith('<li><div style="cursor: pointer;">Bookmark</div></li>');
    		}
    	} else {
    
    		jQuery("div[id^='bookmark_entity_type_']").each(function() {
    			var savedBookmarkKey = jQuery(this).attr("name");
    			var savedBookmark = savedBookmarkKey.substr(savedBookmarkKey.indexOf(":")+1);
    			jQuery("#article_container").find("div[name$='"+savedBookmark+"']").find("#search_result_related_bottom_box04>ul").removeClass("list_search_links").addClass("list_search_links_bookmarked").find("li").replaceWith("<li><div>Bookmarked</div></li>");
    			jQuery("#highlight_article").find("div[name$='"+savedBookmark+"']").find("#search_result_related_bottom_box04>ul").removeClass("list_search_links").addClass("list_search_links_bookmarked").find("li").replaceWith("<li><div>Bookmarked</div></li>");
    			jQuery("#latest_update_container").find("div[name$='"+savedBookmark+"']").find("#latestupdate_bookmark_links>ul").removeClass("list_search_links").addClass("list_search_links_bookmarked").find("li").replaceWith("<li><div>Bookmarked</div></li>");
    		});
    	}
    } catch(error) {}
}

function renderReportsAndServices(subscriptionCategoryCount) {
	// if the category is selected remove the handlers do the image stays in rollover mode, 
	// reset the others so the rollover is intact
	jQuery("li[id^='category_image_container_']").each(function() {
		var container = jQuery(this);
		var container_selector = container.attr("id");
		var container_count = container_selector.substr(container_selector.lastIndexOf("_")+1);
		var element = document.getElementById("div_category_image_container_"+container_count);
		var imageName = element.getAttribute("name");		
		if(container_count == subscriptionCategoryCount) {
			element.onmouseover = "";
			element.onmouseout = "";	
			// Change the active category to hover graphic
			jQuery("#cat" + container_count).html("<img src='http://www.thefuturescompany.com/file_depot/0-10000000/0-10000/1/folder/55/RS-"+imageName+"-hover.jpg' border='0' width='14' height='41' alt=''  />");
		} else {
			element.onmouseover = function() {swapRolloverImage("RS-"+imageName+"-hover.jpg","cat"+container_count,"14");};
			element.onmouseout = function() {swapRolloverImage("RS-"+imageName+".jpg","cat"+container_count,"9");};						
			// change inactive to base graphic
			jQuery("#cat" + container_count).html("<img src='http://www.thefuturescompany.com/file_depot/0-10000000/0-10000/1/folder/55/RS-"+imageName+".jpg' border='0' width='9' height='41' alt=''  />");
		}
	});
	
}

function prepareBookmarkForm(bookmarkLink) {
	var topLevelContainer  = bookmarkLink.parentsUntil(".display_rowleft").parent();	
	var bookmark_entity_type = topLevelContainer.attr("name");									
	var resultRelatedContainer  = bookmarkLink.parentsUntil(".display_rowleft");
	var articleNameContainer = topLevelContainer.find("h3");
	var bookmark_name = articleNameContainer.html()								
	var urlContainer = bookmarkLink.parentsUntil("#search_result_related_bottom_box04").prev();
	var bookmark_url = urlContainer.val();

	bookmarkLink.click(function() {
		showBookmarkForm(resultRelatedContainer, bookmark_name, bookmark_url, bookmark_entity_type);
	});	
}

function prepareLatestUpdateBookmarkForm(bookmarkLink) {    
    var bookmarkAttribute  = bookmarkLink.parentsUntil("#latestupdate_bookmark_links").parent().next();
    var bookmark_name = bookmarkAttribute.attr("id");
    bookmarkAttribute = bookmarkAttribute.next();                           
    var bookmark_url = bookmarkAttribute.attr("id");
    bookmarkAttribute = bookmarkAttribute.next();
    var bookmark_entity_type = bookmarkAttribute.attr("id");    

    bookmarkLink.click(function() {
        showBookmarkForm(bookmarkLink.parentsUntil("#latestupdate_bookmark_links").parent().children().first(), bookmark_name, bookmark_url, bookmark_entity_type);
    }); 
}

// function showBookmarkForm(targetContainer, bookmark_name, bookmark_url,
// bookmark_facets, bookmark_flag, bookmark_entity_type) {
function showBookmarkForm(targetContainer, bookmark_name, bookmark_url, bookmark_entity_type) {
	processBookmarkLinks();
	var addBookmarkForm = jQuery("#search_bookmark_wrapper").clone();
	addBookmarkForm.appendTo(targetContainer.siblings().first());
	addBookmarkForm.toggle();
	addBookmarkForm.find("#bookmark_name").val(bookmark_name);
	addBookmarkForm.find("#bookmark_url").val(bookmark_url);
	addBookmarkForm.find("#bookmark_entity_type").val(bookmark_entity_type);
	createdBookmarkForm = addBookmarkForm;
}

function processBookmarkLinks() {   
    try {
    	destroyBookmarkForm();
    	jQuery("#form_bookmark_save").find("#existing_bookmark_categories_inner").replaceWith(jQuery("#existing_bookmark_categories_list").html());
    	jQuery("#search_results_container").find("#search_result_related_bottom_box04 .list_search_links > li > div").each(function() {
    		prepareBookmarkForm(jQuery(this));		
    	});
        jQuery("#highlight_article").find("#search_result_related_bottom_box04 .list_search_links > li > div").each(function() {
            prepareBookmarkForm(jQuery(this));      
        });  
        jQuery("#latest_update_container").find("#latestupdate_bookmark_links > ul > li > div").each(function() {
            prepareLatestUpdateBookmarkForm(jQuery(this));      
        });  
    } catch(error) {}
}	
			
function submitTFCSearchSaveForm() {	
	processBookmarkLinks();
	toggleSearchTermPreloader(true);
	
	jQuery.ajax({
		async: true,
		url: jQuery("#tfcsearch_save_url").val(),
		type: "POST",
		dataType: "html",
		data: jQuery("#tfc_search_save_form").serialize(),
		cache: false,
		complete: function( res, status ) {				
			if ( status === "success" || status === "notmodified" ) {				
				var returnedContent = jQuery("<div />").append(res.responseText);
				jQuery("#favorite_search_container_inner").replaceWith(returnedContent.find("#favorite_search_container").html());		
				showFavoritesTab("search");		
				toggleSearchTermPreloader(false);
				}			
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); alert(errorThrown); }
	});	
	return false;	
}

function deleteSavedSearch(delete_url) {	
	processBookmarkLinks();
	toggleSearchTermPreloader(true);
	jQuery.ajax({
		async: true,
		url: delete_url,
		type: "POST",
		dataType: "html",
		cache: false,
		complete: function( res, status ) {				
			if ( status === "success" || status === "notmodified" ) {				
				var returnedContent = jQuery("<div />").append(res.responseText);
				if(jQuery("#favorites-interstitial-wrapper").length) {
					jQuery("#favorites-display-container_inner").replaceWith(returnedContent.find("#favorites-display-container").html());
				} else {
					jQuery("#favorite_search_container_inner").replaceWith(returnedContent.find("#favorite_search_container").html());
					showFavoritesTab("search");				
				}
				toggleSearchTermPreloader(false);
			}
			
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); alert(errorThrown); }
	});	
	return false;	
}

function toggleBookmarkError(container) {
    container.find("#error_bookmark_save").toggle();
    container.find("#form_bookmark_save").toggle();    
}

function submitTFCBookmarkSaveForm(container, serialized_data) {
    var bookmark_cat_selection_count = container.find("input:checked").length;
    if(container.find("#new_catbox_container").is(':visible') && container.find("#srch_category").val().trim().length ==0 ) {
        bookmark_cat_selection_count--;
    }    
    if(bookmark_cat_selection_count <=0) {
        toggleBookmarkError(container);
        return false;
    }    
	createdBookmarkForm.find("#form_bookmark_save").toggle();
	createdBookmarkForm.find("#preloader_bookmark_save").toggle();    
    var preSubmitForm = createdBookmarkForm;     
    var formData = "";
    if(jQuery.browser.msie || serialized_data == "") {
        formData = createdBookmarkForm.find("#save_bookmark_form").serialize();
    } else {
        formData = serialized_data;
    }   
    
	jQuery.ajax({
		async: true,
		url: jQuery("#tfcbookmark_save_url").val(),
		type: "POST",
		dataType: "html",
		data: formData,
		cache: false,
		complete: function( res, status ) {				
			if ( status === "success" || status === "notmodified" ) {				
				var returnedContent = jQuery("<div />").append(res.responseText);				
				jQuery("#favorite_bookmark_container_inner").replaceWith(returnedContent.find("#favorite_bookmark_container").html());		
				jQuery("#existing_bookmark_categories_list").find("#existing_bookmark_categories_inner").replaceWith(returnedContent.find("#existing_bookmark_categories_list").html());
				createdBookmarkForm = preSubmitForm;	
				showFavoritesTab("bookmark");
				container.find("#preloader_bookmark_save").toggle();
				container.find("#confirm_bookmark_save").toggle();	  
				if(jQuery("#articlecontent_bookmark_links").length) {     
                    jQuery("#articlecontent_bookmark_links>ul").removeClass("list_search_links").addClass("list_search_links_bookmarked").find("li").replaceWith("<li><div>Bookmarked</div></li>");
				} else {
					renderBookmarkLinks();					
				}    											
			}
			
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); alert(errorThrown); }
	});	
	return false;	
}

function deleteSavedBookmark(delete_url, bookmark_entity_type) {
	processBookmarkLinks();
	toggleSearchTermPreloader(true);
	jQuery.ajax({
		async: true,
		url: delete_url,
		type: "POST",
		dataType: "html",
		cache: false,
		complete: function( res, status ) {				
			if ( status === "success" || status === "notmodified" ) {				
				var returnedContent = jQuery("<div />").append(res.responseText);
				if(jQuery("#favorites-interstitial-wrapper").length) {
					jQuery("#favorites-display-container_inner").replaceWith(returnedContent.find("#favorites-display-container").html());
				} else {
					jQuery("#favorite_bookmark_container_inner").replaceWith(returnedContent.find("#favorite_bookmark_container").html());
					jQuery("#existing_bookmark_categories_list").find("#existing_bookmark_categories_inner").replaceWith(returnedContent.find("#existing_bookmark_categories_list").html());
					showFavoritesTab("bookmark");
					renderBookmarkLinks(bookmark_entity_type);
                    processBookmarkLinks(); 					
				}
				toggleSearchTermPreloader(false);
			}
			
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); alert(errorThrown); }
	});	
	return false;	
}

function doSearchFromHeader() {	
	var searchForm = jQuery("#tfc_search_form");
	var formData = searchForm.serialize();
	var formAction = "/?ct=contentsearch";
	if(jQuery("#search_results_container").length) {	
		return submitTFCSearchRefinementForm(formData);
	} else {
	    if(jQuery.browser.msie) {
	       var searchTermBox = searchForm.find("input[type='text']");	       
	       var searchTerm = searchTermBox.val();
	       searchTermBox.val(stripLeadingAndTrailingQuotes(searchTerm));
	    }
		searchForm.attr("action", formAction);
		searchForm.attr("method", "POST");
		searchForm.submit();
	}

}

function doSearchFromHeaderIfEnterPressed() {
	if(window.event.keyCode == "13") {
		return doSearchFromHeader();
	}
}

function stripLeadingAndTrailingQuotes(str) {
    if(str.length > 0) {
        str=jQuery.trim(str);
        while (str.charAt(0) == "\"" || str.charAt(0) == "'") {
            str = str.substring(1, str.length);
        }
        while (str.charAt(str.length-1) == "\"" || str.charAt(str.length-1) == "'") {
            str = str.substring(0, str.length - 1);
        }
    }
    return str;
}
    
function doSearchFromServicesWapplet(categoryCount) {	
	var searchForm = jQuery("#tfc_services_wapplet_form_"+categoryCount);	
	var formData = searchForm.serialize();
	var formAction = "/?ct=contentsearch&sr_v=bsrun";
	submitReportsandServicesSelection(formData, formAction);	
	renderReportsAndServices(categoryCount);	
	jQuery.cookie("dsfs", null);
	return false;
}

/**
 * Skips the bookshelf and go to advanced search page
 * used for Global Streetscapes and Future Perspectives
 * @param categoryCount
 */
function doAdvancedSearchFromServicesWapplet(categoryCount) {	
	var searchForm = jQuery("#tfc_services_wapplet_form_"+categoryCount);	
	searchForm.submit();
}

function doSearchFromKeyTopicWapplet(topicCount) {
	jQuery.cookie("dsfs", null);	
	var searchForm = jQuery("#tfc_keytopics_form_"+topicCount);
	searchForm.submit();
}


function doSearchFromBookshelf(facetId) {	
	var searchForm = jQuery("#tfc_bookshelf_form_"+facetId);		
	var formData = searchForm.serialize();
	var formAction = "/?ct=contentsearch&sr_v=bsdrun";
	submitReportsandServicesSelection(formData, formAction);
	return false;

}

function doSearchFromBookshelfDetails() {
	jQuery.cookie("dsfs", null);

	var searchForm = jQuery("#tfc_bookshelfdetails_archive_form");
	searchForm.submit();
}


function doSearchFromServices(categoryCount, categoryName) {
	var servicesForm = jQuery("#tfc_services_form"+categoryCount);
	var category_name = jQuery.trim(jQuery("#subscription_cat_"+categoryCount).html());

	/*
	jQuery("div[id^='cat_']").each(function() {
		var selectCat = jQuery(this);
		var cat_selector = selectCat.attr("id");
		var cat_count =cat_selector.substr(cat_selector.lastIndexOf("_")+1);
		if(cat_count == categoryCount) {
			jQuery("#subscription_cat_hidden_"+cat_count).val(cat_id);
		} else {
			jQuery("#subscription_cat_hidden_"+cat_count).val("");
		}
	});
	*/
	
	var formData = servicesForm.serialize();
	var formAction = "/?ct=contentsearch&sr_v=run";
	submitTFCSearchRefinementForm(formData, formAction, category_name);
	jQuery.cookie("dsfs", "true");
	renderReportsAndServices(categoryCount)
	return false;
}

/**
 * set a cookie and redirect to the user home page
 * 
 * @param categoryCount
 */
function doBookshelfSearchFromServices(categoryCount) {
	jQuery.cookie("categoryCount", categoryCount, {path: '/'});
	jQuery.cookie("dsfs", null);	

	window.location = "/";
}


/**
 * this method will submit key topic as a facet using an AJAX call
 * @param facetCount
 */
function doSearchFromKeyTopic(facetCount) {
    var keyTopicsForm = jQuery("#tfc_keytopics_form_"+facetCount);
	var formData = keyTopicsForm.serialize();
	var formAction = "/?ct=contentsearch&sr_v=run";

//    I'm assigning a fake cattegory so the ui block can come off
	submitTFCSearchRefinementForm(formData, formAction,'fakeCat');

    return false;
}

function runSavedSearch(categoryCount) {
	var savedSearchForm = jQuery("#tfc_saved_search_form_"+categoryCount);
	var formData = savedSearchForm.serialize();
	var formAction = "/?ct=contentsearch";
	if(jQuery("#search_results_container").length) {
		return submitTFCSearchRefinementForm(formData);
	} else {
		savedSearchForm.attr("action", formAction);
		savedSearchForm.attr("method", "POST");
		savedSearchForm.submit();
	}
}

function runFavoritesSearch(categoryCount) {
	var favoritesSearchForm = jQuery("#tfc_favorites_search_form_"+categoryCount);
	var formData = favoritesSearchForm.serialize();	
	var formAction = "/?ct=contentsearch&sr_v=run";
	return submitTFCSearchRefinementForm(formData, formAction);
}
	
	
function runSavedBookmarkSearch(bookmarkCount) {
    var bookmarkSearchForm = jQuery("#tfc_favorites_bookmark_search_form_"+bookmarkCount);
    var formData = bookmarkSearchForm.serialize(); 
    var formAction = "/?ct=contentsearch&sr_v=brun";
    if(jQuery("#search_results_container").length && !jQuery("#bookshelf").length) {
        submitTFCSearchRefinementForm(formData, formAction);
        toggleSearchTermPreloader(false);
        return false;
    } else {
        bookmarkSearchForm.attr("action", "/?ct=contentsearch&sr_v=brun");
        bookmarkSearchForm.attr("method", "POST");
        bookmarkSearchForm.submit();    	
    }
}

function runFavoritesBookmarkSearch(bookmarkCount) {
    var bookmarkSearchForm = jQuery("#tfc_favorites_bookmark_search_form_"+bookmarkCount);
    var formData = bookmarkSearchForm.serialize(); 
    var formAction = "/?ct=contentsearch&sr_v=brun";
    return submitTFCSearchRefinementForm(formData, formAction);
}

function submitTFCSearchRefinementForm(serialized_data, action_url, category_name) {	
	if( !action_url) {
		action_url = jQuery("#tfcsearch_run_url").val()
	}
	
	toggleSearchTermPreloader(true);	
	jQuery.ajax({
		async: true,
		url:action_url,
		type: "POST",
		dataType: "html",
		data: serialized_data,
		cache: false,
		complete: function( res, status ) {				
			if ( status === "success" || status === "notmodified" ) {				
				var returnedContent = jQuery("<div />").append(res.responseText);
				if(jQuery("#search_results_container").length) {									
                    													
                    // search terms removed but we need to update the hiddne fields
					jQuery("#search_terms_container_inner").replaceWith(returnedContent.find("#search_terms_container").html());
					
                    jQuery("#search_refine_container_inner").replaceWith(returnedContent.find("#search_refine_container").html());
                    jQuery("#search_results_container_inner").replaceWith(returnedContent.find("#search_results_container").html());	
                    
                    // other categories removed
                    if(jQuery("#sidebox__results_container").length) {
                        jQuery("#sidebox_other_categories_results_container").show();
                        jQuery("#sidebox_other_categories_results_container").find("#sidebox_search_content_inner").replaceWith(returnedContent.find("#other_categories_hidden").html());
                    }				
					 
				} else {
					jQuery("#favorites-display-container").replaceWith(returnedContent.find("#search-results-container_outer").html());
                    if(jQuery("#sidebox_other_categories_results_container").length) {                        
                        jQuery("#sidebox_other_categories_results_container").find("#sidebox_search_content_inner").replaceWith(returnedContent.find("#other_categories_hidden").html());
                        if(jQuery("#search_refine_container_inner input[name='selected_categories']").length) {
                            jQuery("#sidebox_other_categories_results_container").show();
                        }
                    }   					
				}
				                    
                renderBookmarkLinks();                
                processBookmarkLinks();  
                
				toggleSearchTermPreloader(false);             
   
			}
			
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); alert(errorThrown); }
	});		
	return false;	
}

// replace the dynamic-content-container on the landing page with the top level
// facets formatted in the bookshelf grid
function submitReportsandServicesSelection(serialized_data, action_url) {	
	if(!action_url) {
		action_url = jQuery("#tfc_services_wapplet_form_"+categoryCount).action();	
	}
	processBookmarkLinks();
	toggleSearchTermPreloader(true);	
	jQuery.ajax({
		async: true,
		url:action_url,
		type: "POST",
		dataType: "html",
		data: serialized_data,
		cache: false,
		complete: function( res, status ) {				
			if ( status === "success" || status === "notmodified" ) {	
				var returnedContent = jQuery("<div />").append(res.responseText);
				
				if(jQuery("#bookshelf").length) {
                    jQuery("#bookshelf").replaceWith(returnedContent.find("#gwhome-dynamic-content-container").html());
				}  					 				                    
                renderBookmarkLinks();                
                processBookmarkLinks(); 
				toggleSearchTermPreloader(false);                              
			}			
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); alert(errorThrown); }
	});		
	return false;	
}

function showHighlightBanner(category_name) {                
    var article = jQuery("#article_container").find("div[id^=searchResult-]").first().clone();
    jQuery("#highlight_article").find("div").html(article);
    jQuery("#insight_services_highlight_banner").find("div[id$='_banner_image']").hide();
    
    if(category_name) {
	    switch(category_name.toUpperCase()) {
	        case "GLOBAL MONITOR":                          
	            jQuery("#global_monitor_banner_image").show();
	            jQuery("#insight_services_highlight_banner").show();
	            break;
	        case "GLOBAL STREETSCAPES":
	            jQuery("#global_streetscapes_banner_image").show();
	            jQuery("#insight_services_highlight_banner").show();
	            break;              
	        case "INDIA MONITOR":
	            jQuery("#india_monitor_banner_image").show();
	            jQuery("#insight_services_highlight_banner").show();
	            break; 
	        case "LATIN AMERICA MONITOR":
	            jQuery("#latam_monitor_banner_image").show();
	            jQuery("#insight_services_highlight_banner").show();
	            break;
	        case "UK MONITOR":
	            jQuery("#uk_monitor_banner_image").show();
	            jQuery("#insight_services_highlight_banner").show();
	            break;
	        case "US MONITOR":
	            jQuery("#us_monitor_banner_image").show();
	            jQuery("#insight_services_highlight_banner").show();
	            break;                      
	        default:
	        jQuery("#insight_services_highlight_banner").hide();
	    }
    }

}


function displayFavoritesSearches(content_id) {
	toggleSearchTermPreloader(true);
	jQuery.ajax({
		async: true,
		url: "/?ct=tfcsearch&ts_v=disp",
		type: "POST",
		dataType: "html",
		cache: false,
		complete: function( res, status ) {				
			if ( status === "success" || status === "notmodified" ) {				
				var returnedContent = jQuery("<div />").append(res.responseText);
				if(content_id) {
					jQuery("#cont-body-"+content_id).html(returnedContent.find("#favorites-display-container"));
				} else {
					jQuery("#favorites-display-container_inner").replaceWith(returnedContent.find("#favorites-display-container").html());
				}
                if(jQuery("#sidebox_other_categories_results_container").length) {
                    jQuery("#sidebox_other_categories_results_container").hide();
                }	
                
            	toggleSearchTermPreloader(false);
			}
			
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); alert(errorThrown); }
	});	
	return false;	
}

function displayFavoritesBookmarks(content_id) {	
	toggleSearchTermPreloader(true);
	jQuery.ajax({
		async: true,
		url: "/?ct=tfcbookmarks&tb_v=disp",
		type: "POST",
		dataType: "html",
		cache: false,
		complete: function( res, status ) {				
			if ( status === "success" || status === "notmodified" ) {				
				var returnedContent = jQuery("<div />").append(res.responseText);
				if(content_id) {
					jQuery("#cont-body-"+content_id).html(returnedContent.find("#favorites-display-container"));
				} else {
					jQuery("#favorites-display-container_inner").replaceWith(returnedContent.find("#favorites-display-container").html());
				}
                if(jQuery("#sidebox_other_categories_results_container").length) {
                    jQuery("#sidebox_other_categories_results_container").hide();
                }	
                
             	toggleSearchTermPreloader(false);
			}
			
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); alert(errorThrown); }
	});	
	return false;	
}

function gotoPage(page_num) {
	jQuery("#search_results_page").val(page_num);
	var retVal = submitTFCSearchRefinementForm(jQuery("#tfc_search_refinement_form").serialize());
	window.scrollBy(0,-2000);
	return retVal;
}

function clearContentFacet(facet_id) {
	jQuery("#selected_facets_"+facet_id).val("");
	return gotoPage("0");
}

function addContentFacet(facet_id) {
	jQuery("#selected_facets_"+facet_id).val(facet_id);
	return gotoPage("0");
}

function showFavoritesTab(tab_name) {
	if(tab_name == "bookmark") {
		if(jQuery("#favorite_bookmark_tab_leaf").attr("class")=="search_tabs02_item01") {
			jQuery("#favorite_bookmark_tab_leaf").attr("class","search_tabs02_item01_selected");
			jQuery("#favorite_search_tab_leaf").attr("class", "search_tabs02_item02");
			jQuery("div[id^='favorite_container_']").toggle();
		}
	} else if(tab_name == "search") {
		if(jQuery("#favorite_search_tab_leaf").attr("class")=="search_tabs02_item02") {
			jQuery("#favorite_search_tab_leaf").attr("class", "search_tabs02_item02_selected");
			jQuery("#favorite_bookmark_tab_leaf").attr("class","search_tabs02_item01")
			jQuery("div[id^='favorite_container_']").toggle();
		}	
	}
}

function resetSearchCategoriesFlap(categoryName) {
    jQuery("#header_form_search_category_inputs input[type=checkbox]").each(function() {
        var checkbox = jQuery(this);      
        var hiddenInput =  checkbox.next();   
        var categoryLabel = hiddenInput.next();
        if( !categoryName || categoryName == categoryLabel.html() ) {
            checkbox.attr("checked", "checked");  
            hiddenInput.val(checkbox.val());
        } else {
            checkbox.removeAttr("checked");  
            hiddenInput.val("");
        }
        hiddenInput.attr("disabled","disabled");
    }); 
    if(!categoryName) {
        if( jQuery("#search_flap_container").attr("class") == "header_search_container_post_expanded" ) {
            jQuery("#search_flap_container").removeClass("header_search_container_post_expanded");
            jQuery("#search_flap_container").addClass("header_search_container_post_closed");
        }
    }
    jQuery("input[id^='header_search_textbox_']").val("")
}

function toggleSearchCategoriesFlap() {
    processBookmarkLinks();
    jQuery("#search_flap_container").toggleClass(function() {
        if( jQuery(this).attr("class") == "header_search_container_post_closed") {
            jQuery(this).removeClass("header_search_container_post_closed"); 
            jQuery("#header_form_search_category_inputs input[type=checkbox]").each(function() {
                var checkbox = jQuery(this);      
                var hiddenInput =  checkbox.next();         
                if(checkbox.attr("checked")) {
                    hiddenInput.val(checkbox.val());
                    hiddenInput.removeAttr("disabled");
                } else {
                    hiddenInput.val("");
                    hiddenInput.attr("disabled","disabled");
                }
            });                     
            return "header_search_container_post_expanded";
        } else {
            jQuery(this).removeClass("header_search_container_post_expanded");
            jQuery("#header_form_search_category_inputs input[type=hidden]").each(function() {
                var hiddenInput = jQuery(this);       
                hiddenInput.attr("disabled","disabled");
            });             
            return "header_search_container_post_closed";
        }
    });
    jQuery("#flap_expand_categories").toggle();
    jQuery("#flap_contract_switch").toggle();
    jQuery("#flap_expand_switch").toggle();
}

function syncCheckBoxWithHidden(categoryCount) {
	var checkbox = jQuery("#searchflap_category_select_"+categoryCount);
	var hiddenInput = jQuery("#searchflap_category_hidden_"+categoryCount);
	if(checkbox.attr("checked")) {
		hiddenInput.val(checkbox.val());
		hiddenInput.removeAttr("disabled");
	} else {
		hiddenInput.val("");
		hiddenInput.attr("disabled","disabled");
	}
}

function refreshBookmarksAfterShadowBox() {
    jQuery.ajax({
        async: true,
        url: "/?ct=tfcbookmarks&tb_v=lst",
        type: "POST",
        dataType: "html",
        cache: false,
        complete: function( res, status ) {             
            if ( status === "success" || status === "notmodified" ) {               
                var returnedContent = jQuery("<div />").append(res.responseText);                
                jQuery("#favorite_bookmark_container_inner").replaceWith(returnedContent.find("#favorite_bookmark_container").html());      
                jQuery("#existing_bookmark_categories_list").find("#existing_bookmark_categories_inner").replaceWith(returnedContent.find("#existing_bookmark_categories_list").html());
                renderBookmarkLinks();
                processBookmarkLinks();                            
            }
            
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); alert(errorThrown); }
    }); 
    return false;   
}

function shadowBoxClosed() {
	if(jQuery("#existing_bookmark_categories_list").length) {	
	   refreshBookmarksAfterShadowBox();
	}
}

// IE7 barfs on this better version
//function swapRolloverImage(imageName, objName, objWidth)
//{
//	jQuery("#" + objName).html("<img src='http://www.thefuturescompany.com/file_depot/0-10000000/0-10000/1/folder/55/"+imageName+"' border='0' width='"+objWidth+"' height='41' alt=''  />");
//}

function swapRolloverImage(imageName,objName,objWidth)
{
	var obj = document.getElementById(objName);
	var imgTag = "<img src='http://thefuturescompany.com/file_depot/0-10000000/0-10000/1/folder/55/"+imageName+"' border='0' width='"+objWidth+"' height='41' alt=''  />";		
	obj.innerHTML = imgTag;		
	return;
}

var urlParams = {};
(function () {
    var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
       urlParams[d(e[1])] = d(e[2]);
})();

function setCategoryActive( imageName, catCount ) {	
	if ( jQuery.cookie("dsfs") == null )
	{
		catImageName = urlParams["insights_service_name"];
		if ( catImageName )
			catImageName = catImageName.replace("&", "+").replace(" ", "_");
		if( imageName == catImageName )
			jQuery("#cat" + catCount).html("<img src='http://www.thefuturescompany.com/file_depot/0-10000000/0-10000/1/folder/55/RS-"+imageName+"-hover.jpg' border='0' width='14' height='41' alt=''  />");
	}
}


