var NUM_SUGGESTIONS = 10;
var MAX_USER_ROLES = 5;
var showSelfMessagesAfterSend = false;
var showDirectMessagesAfterSend = false;
var numResults = 10;
var currentlySelectedSuggestion = -1;
var suggestion_urls = null;
var feedbackFormVisible = false;
var feedsPage = 1;
var top_fpp = null;
var profile_fpp = null;
var firehose_fpp = null;
var firehose_index_fpp = null;
var source_type = 'news';
var top_feed_ids = "";
var recent_feed_ids = "";
var newest_feed_ids = "";
var oldest_feed_ids = "";
var sort_by = "score";
var feed_page = 1;
var feed_entity_id = -1;
var c_list_dict = new Object();
var p_list_dict = new Object();
var i_list_dict = new Object();
var feed_company_list = "";
var feed_person_list = "";
var feed_industry_list = "";
var featured_ticker = "";
var featured_url = "";
var featured_height = "";
var ticker_list = null;
var ticker = null;
var yesterday_portfolio_value = null;
var holdings = new Object();
var industry_ticker_list = "";
var companies_ticker_list = "";
var industry_override = false;
var recent_ticker_list = new Object();
var company_market_url = "";
var index_market_url = "";
var index_market_ticker = "";
var inactivityMS = 1800000;
var global_description_toggle = "less";
var allowClose = true;
var closeOverride = false;
var expandImg = "";
var collapseImg = "";
var personalize_firehose = false;
var profile_id = -1;
var visibleOverlayId = null;
var visibleOverlayContentId = null;
var getMoreHeadlines = false;
var popoutWindow = null;
var user_id_tracker_shown = -1;
var nonPublicCompanyURIs = new Object()
var publicCompanyURIs = new Object()
var companyURIs = new Object()
var tickerDict = new Object();
var tickerMappings = new Object();
var suggestionTimer = null;
// this might be overwritten in jsincludes_feeds.js
var feedsNowRoundedMinute = 5;
var contact_id_selected = -1;
var tag_id_selected = -1;
var industry_id_selected = -1;
var geo_code_selected = -1;
var connections_data_for_observations_dropdown = null;
var histPosCheckbox = "checked";
var histGeoCheckbox = "";
var histIndCheckbox = "checked";
var contacts_downloaded = false;
var selectedTrackerCenterPaneRow = null;
var trackerDataLabelTabSelected = null;
var currentlyOpenMenus = new Array();

var doHideUpdatesFilters = true;
var global_timestamp = parseInt((new Date()).getTime()/1000)
var global_boa = "before";
var global_activity = "true";
var global_mouse_x = 0;
var global_mouse_y = 0;
var recommendedEntitiesBackfill = new Array();
var recommendedEntitiesBackfillIndex = 0;
var totalRecommendedEntitiesCount = 0;
var totalIgnoredOrTrackedEntitiesCount = 0;

var company_ticker_symbols = new Array();
var my_connections = new Array();
var observation_connections = new Array();
var currently_selected_observation_connection = 0;

var email_re = /^(("[\w-\s]+")|([\w-]+(?:[\.\+][\w-]+)*)|("[\w-\s]+")([\w-]+(?:[\.\+][\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i
var username_re = /^([a-zA-Z0-9_-]+)$/;
var shorten_urls_re = /\b(?:(?:https?:\/\/)(?!bit\.ly)(?!tinyurl\.com)[-\w]+(?:\.\w[-\w]*)+|(?!bit\.ly)(?!tinyurl\.com)(?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\.)+(?:com|edu|biz|gov|in(?:t|fo)|mil|net|org|[a-z][a-z]\.[a-z][a-z])\b)(?=[^\w-]|$)(?::\d+)?(?:\/[^.!,?;"\'<>\(\)\[\]\{\}\s\x7F-\xFF]*(?:[.!,?]+[^.!,?;"\'<>\(\)\[\]\{\}\s\x7F-\xFF]+)*)?/i                  

// used for async calls to make sure no more than one is being done at a time
var ajaxSemaphoreAvailable = true;
var trackedSemaphoreAvailable = true;
var feedsSemaphoreAvailable = true;
var showTrackedNewTimesImmediately = false;
var selectedTrackerFilter = null;
// used for older and newer feed links. stores max and min dates of feeds on the page
var newest_date = null;
var oldest_date = null;

// timers
var asyncTimers = new Object();
var asyncRefreshRates = new Object();

var j = jQuery.noConflict();
var new_tracked_content = null;

var pp_entity_id = -1
var pp_entity_type = "";
var pp_entity_uri = "";

function UserConnection(_user_id, _first_name, _last_name, _user_name, _email, _job_title) {
    this.user_id = _user_id;
    this.first_name = _first_name;
    this.last_name = _last_name;
    this.full_name = _first_name + " " + _last_name;
    this.user_name = _user_name;
    this.email = _email;
    this.job_title = _job_title;
    this.score = 0;
}

function NewTrackedContent() {
    this.html = "";
    this.num_observations = 0;
    this.num_sent_observations = 0;
    this.num_received_observations = 0;
    this.num_headlines = 0;
    this.latest_headline_date = null;
    this.latest_headline_id = -1;
    this.latest_observation_date = null;
    this.latest_observation_id = null;
}

function TrackerFilter() {
    this.filter_name = null;
    this.filter_type = null;
    this.insights = null;
}

function getElem(id) {
   return document.getElementById(id);
}

function has_shortenable_url(str) {

   var result = shorten_urls_re.exec(str);

   if (result == null) {
       return false;
   }

   for (var i = 0; i < result.length; i++) {
       if (result[i].length > 21) {
           return true;
       }
   }

   return false;
}

function addAnotherUserJobTitle(i) {
    var job = getElem("job_" + i);
    if (job != null) {
        j(job).show();
    }
    
    var add = getElem("add_" + i);
    if (add != null) {
        j(add).hide();
    }
}

function toggleMoreInfo(id, expandSrcImg, collapseSrcImg, feed_id) {
    var moreInfo = getElem(id);
    
    var feed = getElem("recent_feed_" + feed_id);
    if (feed != null) {
        j(feed).removeClass("mi_item_new");
    }
    
    if (moreInfo != null) {
        // if the most important item is already expanded, collapse it
        if (moreInfo.style.display == "block") {

            var readMoreLink = getElem("readmore_" + id);
            if (readMoreLink != null)
                readMoreLink.innerHTML = "[expand]";
            var bullet = getElem("bullet_" + id);
            if (bullet != null)
                bullet.src = collapseSrcImg;

            j('#' + id).slideUp(250);
        }
        
        // if the most important item is not yet expanded, expand it.    
        else {

            setTimeout(function() {
                var readMoreLink = getElem("readmore_" + id);
                if (readMoreLink != null)
                    readMoreLink.innerHTML = "[collapse]";
                var bullet = getElem("bullet_" + id);
                if (bullet != null)
                    bullet.src = expandSrcImg;
                
               j('#' + id).slideDown(250);
            }, 50);
        }
    }
}

function showMoreSubs(id) {
   var moreSubsNode = document.getElementById('more_subs_block_' + id);
   var readMoreLink = document.getElementById('more_subs_block_link_' + id);
   if (moreSubsNode != null && readMoreLink != null) {
      if (moreSubsNode.style.display=="block") {
         moreSubsNode.style.display="none";
         readMoreLink.style.visibility="visible";
      } else {
         moreSubsNode.style.display="block";
         readMoreLink.style.visibility="hidden";
      }
   }
}


function toggleHoldingsNooInfo(id, expandSrcImg, collapseSrcImg, ticker, url, height) {
    var moreInfo = getElem(id);
    
    if (moreInfo != null) {
        // if the most important item is already expanded, collapse it
        if (moreInfo.style.display == "block") {
            var bullet = getElem("holdings_more_info_" + ticker);
            if (bullet != null)
                bullet.src = collapseSrcImg;

            j('#' + id).slideUp(250);
        }
        
        // if the most important item is not yet expanded, expand it.    
        else {
            var bullet = getElem("holdings_more_info_" + ticker);
            if (bullet != null)
                bullet.src = expandSrcImg;
            
            j('#' + id).slideDown(250);
            
            setTimeout(function() {
                changeChartSize(url, ticker, height);                
            }, 300);
        }
    }    
}


function toggleMoreCompanies(id) {
    var moreInfo = getElem("more_companies_" + id);
    
    if (moreInfo != null) {
        // if the comp details is already expanded, collapse it
        if (moreInfo.style.display == "block") {
            j('#more_companies_' + id).slideUp(250);
        }
        
        // if the most important item is not yet expanded, expand it.    
        else {
            j('#more_companies_' + id).slideDown(250);
        }
    }
}

function submitTypeAndSearch(num) {
    var search_entity_type_button = getElem("search_entity_type_button");
    if (search_entity_type_button != null) {
        changeSearchType(search_entity_type_button.value, num);
    }  
}

function changeSearchType(type, num) {
    var search_entity_type = getElem("search_entity_type");
    if (search_entity_type != null) {
        search_entity_type.value = type;
    }
    
    var search_entity_type_button = getElem("search_entity_type_button");
    if (search_entity_type_button != null) {
        search_entity_type_button.value = type;
    }
    
    var dropdown_item = getElem("search_dropdown_item_all");
    if (dropdown_item != null) {
        if (type == null || type == "all") {
            dropdown_item.className = "item selected";
        } else {
            dropdown_item.className = "item";
        }
    }
    
    var dropdown_item = getElem("search_dropdown_item_company");
    if (dropdown_item != null) {
        if (type == null || type == "company") {
            dropdown_item.className = "item selected";
        } else {
            dropdown_item.className = "item";
        }
    }
    
    var dropdown_item = getElem("search_dropdown_item_person");
    if (dropdown_item != null) {
        if (type == null || type == "person") {
            dropdown_item.className = "item selected";
        } else {
            dropdown_item.className = "item";
        }
    }
    
    var dropdown_item = getElem("search_dropdown_item_user");
    if (dropdown_item != null) {
        if (type == null || type == "user") {
            dropdown_item.className = "item selected";
        } else {
            dropdown_item.className = "item";
        }
    }
    
    if (num == null)
        submitSearch(-1);
    else
        submitSearch(num);
}

/*
var tickers = ["MSFT","YHOO","GE","WL"];
for (var t=0; t < tickers.length; t++) {
    document.write("<a id='" + tickers[t] + "link' class='visitedornot' href='http://www.google.com/finance?q=" + tickers[t] + "'>" + tickers[t] + "</a>");
}

j(document).ready(function(){
    var link = null;
    var s = "";
    for (var t=0; t < tickers.length; t++) {
        link = getElem(tickers[t] + "link");
        if (mys_getLinkColor(link) == "#ffffff") {
            s += "visited " + tickers[t] + "<br/>";
        } else {
            s += "did not visited " + tickers[t] + "<br/>";                                            
        }
    }
    
    var visited = getElem("visitedhistory");
    if (visited != null) {
        j(visited).html(s);
    }
});
*/

function mys_getLinkColor(node) {
    res = '';
    if(node.currentStyle) {
       res = node.currentStyle.color;
    }
    else if(window.getComputedStyle) {
       res = window.getComputedStyle(node,null).color;
    }
    return mys_rgbToHexColor(res);
}


function mys_rgbToHexColor(v) { 
    // E.g. 'rgb(5,2,11)' converts to "#05020b". All other formats returned unchanged.
    var i;
    v = v.split('(');
    if (!v[1])
        return v[0];
    v = v[1].replace(/ /g, '').replace(/\)/, '');
    v = v.split(',');
    for (i=0; i < v.length; i++) {
        v[i] = Number(v[i]).toString(16);
        if(v[i].length == 1)
            v[i] = '0' + v[i];
    }
    return '#' + v.join('');
}


function toggleProfileButtonEmbedCode() {
    var embeddedProfileButton = getElem("embeddedProfileButton");
    if (embeddedProfileButton != null) {
        j(embeddedProfileButton).toggle();
    }
}

// submit the search or selected suggestion
function submitSearch(num) {
    var type = 'all';
    var search_entity_type = getElem("search_entity_type");
    if (search_entity_type != null) {
        type = search_entity_type.value;
    }
    var type_button = 'all';
    var search_entity_type_button = getElem("search_entity_type_button");
    if (search_entity_type_button != null) {
        type_button = search_entity_type_button.value;
    }

    var search_text = getElem("search_text");
    if (search_text != null) {
        type_plural = "All";
        if (type_button == "company")
            type_plural = "Companies"
        else if (type_button == "person")
            type_plural = "People"
            
        j(search_text).html("Search&nbsp;" + type_plural);    
    }

    var query = document.getElementById("q");
    if (trim(escape(query.value)) == "") {
        return;
    }
    
    var search_loading = getElem("search_loading_img");
    if (search_loading != null) {
        j(search_loading).show();
    }
    
    
    if (num > -1) {
       var sugg = document.getElementById('autoSuggestion_' + num);
       if (sugg != null)
          sugg.className = "autosugg autosugg_submitted";
       
       window.location = "/" + suggestion_urls[num];
    } else {
        setTimeout(function () {
            window.location = "/search?q=" + escape(query.value) + "&etype=" + type + "&etype_button=" + type_button;            
        },0);
    }
}


function createAccount(url) {
    setTimeout(function () {
        window.location = url;            
    },0);
}

function toggleSearchDropdown() {
    var dropdown = getElem("search_dropdown");
    if (dropdown!=null) {
        j(dropdown).toggle();
    }
}

function closeSearchDropdown() {
    var dropdown = getElem("search_dropdown");
    if (dropdown!=null) {
        j(dropdown).hide();
    }
}

function closeSuggestions() {
   var dropDown = document.getElementById("drop_down");
   if (dropDown != null)
      dropDown.style.display = "none";
   
   currentlySelectedSuggestion = -1;
}


// change style of previously selected and currently selected suggestion
function selectSuggestion(i) {
   var sugg = document.getElementById('autoSuggestion_' + currentlySelectedSuggestion);
   if (sugg != null)
      sugg.className = "autosugg autosugg_notselected";
  
   sugg = document.getElementById('autoSuggestion_' + i);
   if (sugg != null)
      sugg.className = "autosugg autosugg_selected";

   currentlySelectedSuggestion = i;
}

function maybeSubmit(event, func) {
   if (event.keyCode == 13) {
      eval(func);
   }
   event.cancelBubble = true;
}

function navigateSuggestions(event) {
   // if up or down arrow is pressed
   // if return key is pressed
   if (event.keyCode == 13) {
      submitTypeAndSearch(currentlySelectedSuggestion);
   }

   /*
   else if (event.keyCode == 40 || event.keyCode == 38) {      
      var sugg = document.getElementById('autoSuggestion_' + currentlySelectedSuggestion);
      if (sugg != null)
         sugg.className = "autosugg autosugg_notselected";

      if (event.keyCode == 40) {         
         currentlySelectedSuggestion += 1;
         if (currentlySelectedSuggestion > numResults-1) {
            currentlySelectedSuggestion = numResults-1;
         }
      } else if (event.keyCode == 38) {
         currentlySelectedSuggestion -= 1;
         if (currentlySelectedSuggestion < 0) {
            currentlySelectedSuggestion = 0;
         }
      } 
      
      // select the correct entry
      var sugg = document.getElementById('autoSuggestion_' + currentlySelectedSuggestion);
      if (sugg != null)
         sugg.className = "autosugg autosugg_selected";
   }
   
      // if esc key is pressed or query length is 0
   else if (event.keyCode == 27) {
      closeSuggestions();
   }

   */
}

function changeStyle(onOrOff) {
   if (onOrOff == 1) {
      document.getElementById("q").className = "inputBox inputSelected";
   } else {
      document.getElementById("q").className = "inputBox inputNotSelected";     
   }
}

function loadSuggestions(event, str) {
    /*
    var dropDown = document.getElementById("drop_down");
    if (str != null)
       query = trim(str);
    
    // if keystroke is pressed and there's something in the input box
    if (query.length > 0 && !(event.keyCode == 40 || event.keyCode == 38 || event.keyCode == 27)) {
      
        suggestion_urls = new Object();  
        var html = "";
        numResults = 0;
        if (suggestionTimer != null) {
            clearTimeout(suggestionTimer);
        }
        
        suggestionTimer = setTimeout(function() {
            j.getJSON("/search/suggest/?q=" + query + "&num_results=" + NUM_SUGGESTIONS,
               function(data){
                  j.each(data, function(i, result) {
                     html += "<div class='autosugg autosugg_notselected' id='autoSuggestion_" + i + "' "
                           + "onMouseOver='javascript:selectSuggestion(" + i + ");' "
                           + "onMouseDown='javascript:submitSearch(" + i + ");'>" //window.location=\"/" + result.entity_type + "/" + result.encoded_name + "\"'>"
                           + "<table><tr><td class='ticker'>" + result.ticker + "</td><td class='name'>" + result.name + "</td></tr></table>"
                           + "</div>";
                     suggestion_urls[i] = result.entity_type + "/" + result.uri;
                     numResults++;
                  });
                  
                  // possibly show or hide the drop down if there are results to show (or not)
                  if (dropDown != null) {
                     if (numResults > 0)
                        dropDown.style.display = "block";
                     else
                        dropDown.style.display = "none";
                  }  
                  dropDown.innerHTML = html;
               }
            );                   
        }, 200);
    }
    */
}

function checkTime(i) {
   if (i < 10) {
      i="0" + i;
   }
   return i;
}
/**
 * return the text for each tweet. If it's less than 60 min ago,
 * return "X min ago", otherwise return the date
 */
function getTwitterDateNode(created_at) {
   var month=new Array(12);
   month[0]="Jan";
   month[1]="Feb";
   month[2]="Mar";
   month[3]="Apr";
   month[4]="May";
   month[5]="June";
   month[6]="July";
   month[7]="Aug";
   month[8]="Sep";
   month[9]="Oct";
   month[10]="Nov";
   month[11]="Dec";

   var twitterDate = new Date(created_at);
   var todaysDate = new Date();
   var retVal = "";
   var urgent = false;
   
   secDiff = (todaysDate.getTime() - twitterDate.getTime())/1000;
   if (secDiff < 60) {
      retVal = secDiff.toFixed(0) + " sec ago";
      urgent = true;
   }
   // if more than a minute ago, put "# min ago"
   else if (secDiff/60 < 60) {
      retVal = (secDiff/60).toFixed(0) + " min ago";
      urgent = true;
   }
   // if more than an hour ago, put "# hours ago"
   else if (secDiff/60/60 < 24) {
      retVal = (secDiff/60/60).toFixed(0) + " hour" + ((secDiff/60/60).toFixed(0) > 1 ? "s" : "") + " ago";
   }
   // if more than a day ago, put "# days ago"
   else if (secDiff/60/60/24 < 7) {
      retVal = (secDiff/60/60/24).toFixed(0) + " day" + ((secDiff/60/60/24).toFixed(0) > 1 ? "s" : "") + " ago";
   }
   // if more than a week ago, just put the date
   else {
      retVal = month[twitterDate.getMonth()] + " "
         + twitterDate.getDate() + ", " + twitterDate.getFullYear() + ", " + twitterDate.getHours()
         + ":" + checkTime(twitterDate.getMinutes()) + ":" + checkTime(twitterDate.getSeconds());
   }
   
   var timeNode = document.createElement("span");
   timeNode.className = "tweets_time" + (urgent?" tweets_urgent":"");            
   timeNode.innerHTML = retVal;
            
   return timeNode;
}

function trim(stringToTrim) {
    if (stringToTrim)
    	return stringToTrim.replace(/^\s+|\s+$/g,"");
    
    return stringToTrim
}

function emphasizeQuery(text, query) {
   query = trim(query);

   var retVal = "";
   var from = 0;
   var index = text.toLowerCase().indexOf(query.toLowerCase(), from);
   while (index >= 0) {
      retVal += text.substring(from, index) + "<span class='tweets_self'>" + text.substring(index, index+query.length) + "</span>";
      from = index+query.length;
      index = text.toLowerCase().indexOf(query.toLowerCase(), from);
   }   
  
   retVal += text.substring(from, text.length);
   
   return retVal;
}

function replaceURLWithLink(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
    return text.replace(exp,"<a href='$1'>[link]</a>"); 
}



/**
 * s the twitter search query
 * n the max number of tweets to show
 **/
function doTweets(s, n) {
   if (n == null)
      n = 5;

   // show loading
   var loadingImg = document.getElementById("tweets_loading_img");
   loadingImg.style.display = "block";

   var tweetsContent = document.getElementById("tweets_content");
   tweetsContent.innerHTML = "";            
   
   j.getJSON("/remote/twitter/?q=" + s,
      function(data){
       
         setTimeout(function() {
            var loadingImg = document.getElementById("tweets_loading_img");
            loadingImg.style.display = "none";
            
            var refreshNode = document.createElement("a");
            refreshNode.className = "tweets_refresh";
            refreshNode.href = "javascript:doTweets('" + s + "'," + n + ")";
            refreshNode.innerHTML = "refresh";
            tweetsContent.appendChild(refreshNode);
            
            // if no tweets available
            if (data.results.length == 0) {
               var noContentNode = document.createElement("div")
               noContentNode.innerHTML = "No tweets available for \"" + s + "\"";
               noContentNode.className = "tweets_loading tweets_none";
               tweetsContent.appendChild(noContentNode);
            }
            
            j.each(data.results, function(i, tweet){
               var tweetNode = document.createElement("div");
               tweetNode.className = "tweets_item";
               
               var imgNode = document.createElement("img");
               imgNode.width = "48";
               imgNode.height = "48";
               imgNode.src = tweet.profile_image_url;
               imgNode.className = "tweets_logo";
               
               var userNode = document.createElement("a");
               userNode.href = "http://www.twitter.com/" + tweet.from_user;
               userNode.innerHTML = tweet.from_user;
               
               var timeNode = getTwitterDateNode(tweet.created_at);
               
               var textNode = document.createElement("div");
               textNode.className = "tweets_tweet";
               tweet.text = replaceURLWithLink(tweet.text);
               textNode.innerHTML = emphasizeQuery(tweet.text, s);
               
               tweetNode.appendChild(imgNode);
               tweetNode.appendChild(userNode);
               tweetNode.appendChild(document.createTextNode(" - "))
               tweetNode.appendChild(timeNode);
               tweetNode.appendChild(document.createTextNode(":"))
               tweetNode.appendChild(textNode);
   
               tweetsContent.appendChild(tweetNode);
               if ( i == n-1 ) return false;
            });
         
         }, 100);

      });
}



function loadNewFeed() {
   setTimeout(function() {
      var newFeed = document.getElementById("newFeed");       
      j('#newFeed').slideDown(500);
      j('#newFeed').fadeIn(500).animate({backgroundColor:"#f1b5b5"}, 500).animate({backgroundColor:"#fae4e4"}, 1000).animate({backgroundColor:"#FFFFFF"}, 5000);

   }, 50);   
}


function changeFeedSource(type, option_to_select, label) {
    setCookie("recentFeeds_type", type, 10000);
    
    source_type = type;
    
    var feed_source_type = getElem("recent_mi_feed_source");
    if (feed_source_type != null) {
        feed_source_type.innerHTML = label;
    }
    
    var dropdown_options = ["feed_source_all", "feed_source_news", "feed_source_press_releases", "feed_source_filings"];
    for (option in dropdown_options) {
        var t = getElem(dropdown_options[option]);
        if (t != null)
            t.className = "";
    }
    
    var t2 = getElem(option_to_select);
    if (t2 != null)
        t2.className = "notlinked";
    
    refreshFeeds(global_timestamp, global_boa, false, false, type, industry_list, "replace");
}


function toggleTrackerChangeAlert() {
   var alert = getElem("tracker_changed_alert");
   j(alert).hide();
}

function hideNewButton(id) {
    j("#" + id + "_new").fadeOut("1000");
}


function unHighlightNewFeed(id) {
    var f = getElem(id);
    if (f != null) {
        f.className = f.className.replace(/mi_item_new/g, "");
    }
}

function highlightNewFeed(id) {
    
    var newMsg = getElem(id + "_new");
    if (newMsg != null) {
        newMsg.style.display = "block";
        j("#" + id + "_new").fadeIn("200");
        setTimeout(function() {
            hideNewButton(id);
        }, 10000)    
    }
    
    
    var f = getElem(id);
    if (f != null) {
        f.className = f.className + " mi_item_new";
        setTimeout(function() {
            unHighlightNewFeed(id);
        }, 10000)    
    }

    /*
   setTimeout(function() {
      j('#' + id).animate({backgroundColor:"#fbf4e8"}, 500).animate({backgroundColor:"#EFEFEF"}, 3000);
   }, 50);

    setTimeout(function() {
      var f = getElem(id);
      if (f != null) {
        f.style.backgroundColor = "#EFEFEF";
      }
   }, 4000);
    */
}


function hideBreakingNews(breaking_id) {
    var breaking = getElem("breaking_news_content");
    if (breaking != null) {
        j(breaking).slideUp(200);
    }
    setCookie("closedBreaking_" + breaking_id, "true", 10000);
}

function getTopHeadlines() {
    var mark_new = 1

    if (!feedsSemaphoreAvailable)
        return
   
    feedsSemaphoreAvailable = false;
    ajaxSemaphoreAvailable = false;
    var top_feed = getElem("top_feed_content");
    j('#new_top_feed_alert').hide();
    j('#loading_top_feed_alert').show();
    
    var d = new Date();
    var unique = d.getTime();

    var url = "/feed/top/?fpp=" + top_fpp + "&visible_ids=" + top_feed_ids + "&mark_new=" + mark_new + "&unique=" + unique;
    j.ajax({
        type: "GET",
        url: url,
        cache:false,
        success:
            function(data) {
                if (data) {
                    var data_array = data.split("<!--split-the-top-->");
                    var top_data = data_array[0];
                    var top_other_data = data_array[1];
                    var featured_data = data_array[2];
                    
                    j("#top_feed_content").html(top_data);
                    j("#top_other_feed_content").html(top_other_data);
                    j("#featured_item_content").html(featured_data);
                    
                    var featured_ticker_input = getElem("featured_ticker_input");
                    if (featured_ticker_input != null) {
                        featured_ticker = featured_ticker_input.value;
                    }
                    
                    changeChartSizeFeatured(featured_url, featured_ticker, featured_height);

                    var top_feed_id_list_node = getElem("top_feed_id_list_" + unique);
                    if (top_feed_id_list_node != null)
                        top_feed_ids = top_feed_id_list_node.value;
                    
                    ajaxSemaphoreAvailable = true;
                    feedsSemaphoreAvailable = true;
                    j('#loading_top_feed_alert').fadeOut(250);
                }
            }
    });
}

function getTimestamp(secAgo) {
    var d = new Date();   
    var timestamp = parseInt(d.getTime()/1000 - secAgo)
    var modulo = timestamp % (feedsNowRoundedMinute*60)
    
    timestamp -= modulo;
    if (modulo > 0)
        timestamp += (feedsNowRoundedMinute*60);
        
    return timestamp;
}

function getOlderFeeds() {
    var timestamp = parseInt(oldest_date);
    refreshFeeds(timestamp, "before", true, false, source_type, industry_list, "replace");
    window.location = "#";
}

function getNewerFeeds() {
    var timestamp = parseInt(newest_date);
    refreshFeeds(timestamp, "after", true, false, source_type, industry_list, "replace");
    window.location = "#";
}

function getOlderHeadlines() {
    var timestamp = parseInt(oldest_date);
    refreshHeadlines(timestamp, "before", true, false, "append");
}

function getNewerHeadlines() {
    var timestamp = parseInt(newest_date);
    refreshHeadlines(timestamp, "after", true, false, "prepend");
}

function getTimedFeeds(secAgo, boa, replace) {
    if (replace == null) {
        replace = "replace";
    }
    
   var timestamp = getTimestamp(secAgo)
   
   markNew = false
   if (secAgo == 0)
      markNew = true

   refreshFeeds(timestamp, boa, false, markNew, source_type, industry_list, replace);   
}


function getTimedHeadlines(secAgo, boa, replace) {
    if (replace == null) {
        replace = "replace";
    }
    
   var timestamp = getTimestamp(secAgo)
   
   markNew = false
   if (secAgo == 0) {
      markNew = true;
      getMoreHeadlines = true;
   }

   refreshHeadlines(timestamp, boa, false, markNew, replace);   
}


function prepRefreshHeadlines(timestamp, boa, fpp, replace) {
    feedsSemaphoreAvailable = false;
    ajaxSemaphoreAvailable = false;
    if (replace == "replace") {
         j('#new_recent_feed_alert').hide();
         j('#tracker_changed_alert').hide();
         j('#loading_recent_feed_alert').show();    
    }
        
    var firehose_user_title = getElem("firehose_user_title");
    if (firehose_user_title != null) {
        j(firehose_user_title).html("Loading");
    }
    
    if (boa == "before" && replace == "append") {
        var older_loading_button = getElem("older_loading_image");
        if (older_loading_button != null) {
            older_loading_button.style.visibility = "visible";
        }       
    } else {
        var newer_loading_button = getElem("newer_loading_image");
        if (newer_loading_button != null) {
            newer_loading_button.style.visibility = "visible";
        }       
    }

    var industry_filter_cb = getElem("industry_filter_cb");

    if (replace == "replace")
        global_timestamp = timestamp;

    global_boa = boa;

    var recent_feed = getElem("recent_feed");
    var newFeedsAlert = getElem("newRecentFeedAlertCount");
    if (getMoreHeadlines && newFeedsAlert != null && newFeedsAlert.innerHTML != "" && parseInt(newFeedsAlert.innerHTML) > fpp) {
         getMoreHeadlines = false;
         //fpp = newFeedsAlert.innerHTML;
         newFeedsAlert.innerHTML = "";
    }
   
    feed_company_list = "";
    for (c in c_list_dict) {
        feed_company_list += c_list_dict[c] + ","
    }
    if (feed_company_list != "") {
        feed_company_list = feed_company_list.substring(0, feed_company_list.length-1)
    }
    
    feed_person_list = "";
    for (p in p_list_dict) {
        feed_person_list += p_list_dict[p] + ","
    }
    if (feed_person_list != "") {
        feed_person_list = feed_person_list.substring(0, feed_person_list.length-1)
    }
    
    feed_industry_list = "";
    for (i in i_list_dict) {
        feed_industry_list += i_list_dict[i] + ","
    }
    if (feed_industry_list != "") {
        feed_industry_list = feed_industry_list.substring(0, feed_industry_list.length-1)
    }
    
    // get industry from dropdown if it exists
    var industry_select = getElem("industry_select");
    if (feed_industry_list == "" && industry_select != null && parseInt(industry_select.value) > 0) {
        feed_industry_list = industry_select.value;
    }

}

function refreshHeadlines(timestamp, boa, doExceptions, markNew, replace) {
    if (!feedsSemaphoreAvailable)
       return
    
    if (recent_feed_ids != null) {
        var recent_list = recent_feed_ids.split(",");
        if (recent_list.length >= 1000) {
            replace = "replace";
        }
    }

    // show loading
    if (boa != "before" && boa != "after") {
        boa = "before";
    }
    
    var fpp = firehose_fpp;
    //if (replace == "replace" && (("" + window.location).indexOf("headlines") >= 0 || ("" + window.location).indexOf("firehose") >= 0 || ("" + window.location).indexOf("mytracker") >= 0)) {
    if ((("" + window.location).indexOf("headlines") >= 0 || ("" + window.location).indexOf("firehose") >= 0 || ("" + window.location).indexOf("my/tracker") >= 0)) {
        fpp = firehose_index_fpp;
    }
    
    prepRefreshHeadlines(timestamp, boa, fpp, replace);    

    var mark_new = 0
    if (markNew)
        mark_new = 1
      
   
    var feed_style = "minimal";
    var feed_style_node = getElem("feed_style");
    if (feed_style_node != null) {
         feed_style = feed_style_node.value;
    }

    var d = new Date();   
    var unique = d.getTime();
    
    var url = "/feed/date/";
    var params = "industry_list=" + feed_industry_list
                        + "&company_list=" + feed_company_list
                        + "&person_list=" + feed_person_list
                        + "&feed_style=" + feed_style;
    
    if (!personalize_firehose) {
        params += "&source_types=" + source_types;
    }

    params +="&fpp=" + fpp
        + "&visible_ids=" + recent_feed_ids
        + "&mark_new=" + mark_new
        + "&boa=" + boa
        + "&profile_id=" + profile_id
        + "&unique=" + unique
        + "&ts=" + parseInt(timestamp);
                        
    if (doExceptions) {
        if (replace == "replace")
            params += "&feed_ids=" + recent_feed_ids;
        else if (replace == "prepend")
            params += "&feed_ids=" + newest_feed_ids;
        else if (replace == "append")
            params += "&feed_ids=" + oldest_feed_ids;
    }
    
    params += "&user_id_filter=" + user_id_tracker_shown;
    
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
                    var loading = getElem("loading_recent_feed_alert");
                    if (loading != null) {
                        loading.innerHTML = "Slight glitch. Try again."
                    }
                    setTimeout(function() {
                        ajaxSemaphoreAvailable = true;
                        feedsSemaphoreAvailable = true;
                        j('#loading_recent_feed_alert').fadeOut(100);
                        
                        setTimeout(function() {
                            loading.innerHTML = "loading updates ...";
                        }, 200);
                    }, 1500);
            },
        success:
            function(data){
                if (data) {
                    if (replace=="replace") {
                        j("#recent_feed").html(data);
                        //window.location = "#";
                    } else if (replace=="prepend") {
                        j("#recent_feed").prepend(data);
                        //recent_feed.scrollTop = 0; //objDiv.scrollHeight;
                    } else {
                        j("#recent_feed").append(data);
                    }
                   
                    var recent_feed_ids_node = getElem("recent_feed_id_list_" + unique);
                    if (recent_feed_ids_node != null) {
                        if (replace == "replace") {
                            recent_feed_ids = recent_feed_ids_node.value;
                            newest_feed_ids = recent_feed_ids_node.value;
                            oldest_feed_ids = recent_feed_ids_node.value;
                        }
                        else if (replace == "append") {
                            recent_feed_ids += "," + recent_feed_ids_node.value;
                            oldest_feed_ids = recent_feed_ids_node.value;
                        }
                        else if (replace == "prepend") {
                            recent_feed_ids += "," + recent_feed_ids_node.value;
                            newest_feed_ids = recent_feed_ids_node.value;                            
                        }
                    }
                    var feed_page_node = getElem("feed_page_" + unique);
                    if (feed_page_node != null && replace == "replace")
                        feed_page = feed_page_node.value;
        
                    var oldest_date_node = getElem("oldest_date_" + unique);
                    if (oldest_date_node != null && (replace == "append" || replace == "replace"))
                        oldest_date = oldest_date_node.value;
                        
                    var newest_date_node = getElem("newest_date_" + unique);
                    if (newest_date_node != null && (replace == "prepend" || replace == "replace")) 
                        newest_date = newest_date_node.value;
                        
                    var recent_mi_feed_title_input_node = getElem("recent_mi_feed_title_input_" + unique);
                    var recent_mi_feed_title_node = getElem("recent_mi_feed_title_" + unique);
                    if (recent_mi_feed_title_input_node != null && recent_mi_feed_title_node != null)
                        recent_mi_feed_title_node.innerHTML = recent_mi_feed_title_input_node.value;
                    
                    var source_types_input_node = getElem("source_types_title_" + unique);
                    var headlines_source_title = getElem("headlines_source_title");
                    if (source_types_input_node != null && headlines_source_title != null)
                        headlines_source_title.innerHTML = source_types_input_node.value;
                    
                    var tracker_types_input_node = getElem("tracker_types_title_" + unique);
                    var headlines_tracker_title = getElem("headlines_tracker_title");
                    if (profile_id < 0 && tracker_types_input_node != null && headlines_tracker_title != null) {
                        headlines_tracker_title.innerHTML = tracker_types_input_node.value;
                        if (tracker_types_input_node.value != "All") {
                            var firehose_title = getElem("firehose_user_title");
                            if (firehose_title != null) {
                                j(firehose_title).html(tracker_types_input_node.value);
                            }
                            
                            var filter_user_title = getElem("filter_user_title");
                            if (filter_user_title != null) {
                                j(filter_user_title).html(tracker_types_input_node.value);
                            }
                            
                            /*
                            filter_user_title = getElem("filter_companies_user_title");
                            if (filter_user_title != null) {
                                j(filter_user_title).html(tracker_types_input_node.value);
                            }
                            
                            filter_user_title = getElem("filter_people_user_title");
                            if (filter_user_title != null) {
                                j(filter_user_title).html(tracker_types_input_node.value);
                            }
                            
                            filter_user_title = getElem("filter_industries_user_title");
                            if (filter_user_title != null) {
                                j(filter_user_title).html(tracker_types_input_node.value);
                            }
                            */
                        }
                    }
                    
                    var show_newer_link_node = getElem("show_newer_link_" + unique);
                    var show_newer_link = null;
                    if (show_newer_link_node != null)
                        show_newer_link = show_newer_link_node.value;
                    
                    var newer_button = getElem("newer_button_1");
                    if (newer_button != null && replace != "append") {
                       if (show_newer_link == "True") {
                            newer_button.style.display = "block";
                           newer_button.className = "recent_button";
                           newer_button.onclick = getNewerHeadlines;
                       } else {
                          //newer_button.className = "recent_button disabled";
                          newer_button.style.display = "none";
                          newer_button.onclick = doNothing;
                       }
                    }
           
                    newer_button = getElem("newer_button_2");
                    if (newer_button != null && replace != "append") {
                       if (show_newer_link == "True") {
                            newer_button.style.display = "block";
                           newer_button.className = "recent_button";
                           newer_button.onclick = getNewerHeadlines;
                       } else {
                          //newer_button.className = "recent_button disabled";
                          newer_button.style.display = "none";
                          newer_button.onclick = doNothing;
                       }
                    }
                        
                    var newer_loading_button = getElem("newer_loading_image");
                    if (newer_loading_button != null) {
                        newer_loading_button.style.visibility = "hidden";
                    }
                     
                    var show_older_link_node = getElem("show_older_link_" + unique);
                    var show_older_link = null;
                    if (show_older_link_node != null)
                        show_older_link = show_older_link_node.value;
                    
                    var older_button = getElem("older_button_1");
                    if (older_button != null && replace != "prepend") {
                       if (show_older_link == "True") {
                           older_button.className = "recent_button";
                           older_button.onclick = getOlderHeadlines;
                       } else {
                          older_button.className = "recent_button disabled";
                          older_button.onclick = doNothing;
                       }
                    }
                    
                    older_button = getElem("older_button_2");
                    if (older_button != null && replace != "prepend") {
                       if (show_older_link == "True") {
                           older_button.className = "recent_button";
                           older_button.onclick = getOlderHeadlines;
                       } else {
                          older_button.className = "recent_button disabled";
                          older_button.onclick = doNothing;
                       }
                    }
                    
                    var older_loading_button = getElem("older_loading_image");
                    if (older_loading_button != null) {
                        older_loading_button.style.visibility = "hidden";
                    }
                    
                    ajaxSemaphoreAvailable = true;
                    feedsSemaphoreAvailable = true;
                    j('#loading_recent_feed_alert').hide();
                }
            }
   });
}

function doNothing() {}

function focusSearch() {
   document.getElementById('q').focus();
}


function transactionSort(entityType, entityEncodedName, ticker) {
    var ticker_select = getElem("trans_ticker_select");
    if (ticker_select != null) {
        ticker = ticker_select.value;    
    }
    
    year = ""
    var year_select = getElem("trans_year_select");
    if (year_select != null) {
        year = year_select.value;    
    }
    
    window.location = "/" + entityType + "/" + entityEncodedName + "/insider_trades/?y=" + year + "&ts=" + ticker;
        
}

function selectAssocPeopleByRole(uri) {
    var cu = "";
    var role_select = getElem("role_select");
    if (role_select != null) {
        cu = role_select.value;
    }

    window.location = uri + "?cu=" + cu;    
}

function compSort(entityType, entityEncodedName) {
    year = ""
    var year_select = getElem("comp_year_select");
    if (year_select != null) {
        year = year_select.value;    
    }
    
    window.location = "/" + entityType + "/" + entityEncodedName + "/compensation/?y=" + year;
        
}

function signup(key) {
    extra = ""
    if (key != null) {
        extra = "link=" + key + "&";
    }
    
    extra += "prev_url=" + window.location;
    
    window.location = "/account/signup/?" + extra;    
}

function logout() {
    var prev_url = window.location + "";
    if (prev_url.indexOf("/account/") >= 0)
        prev_url = null;
        
    var loc = "/account/do_logout/";
    if (prev_url)
        loc += "?prev_url=" + prev_url;
    
    window.location = loc;
}


function login(prev_url) {
    var new_location = "/account/login/";
    if (prev_url != null) {
        new_location += "?prev_url=" + prev_url
    }
    window.location = new_location;    
}

function toggleAllImportedUsers(prefix) {
    for (var i=0; i < document.import_contacts_form.elements.length; i++) {
        var parts = document.import_contacts_form.elements[i].id.split("_");
        if (parts[0] == prefix && document.import_contacts_form.elements[i].type=="checkbox") {
            if (!document.import_contacts_form.elements[i].disabled)
                document.import_contacts_form.elements[i].checked = eval('document.import_contacts_form.checkall_' + prefix + '.checked');
        }
    }    
}

function changePassword() {
    var theForm = document.forms["form1"];

    // validate email
    var emailInput = theForm.email;
    if (emailInput != null && !emailInput.value.match(email_re)) {
        alert("'" + emailInput.value + "' is not a valid email address.");
        return false;
    }
    
    // validate passwords
    var password = theForm.password.value;
    var repeat_password = theForm.repeat_password.value;
    if (password.length == 0) {
        alert("Your password cannot be blank.");
        return false;
    }
    
    if (password.length < 3) {
        alert("Your password must be at least 3 characters.");
        return false;
    }
    
    if (password != repeat_password) {
        alert("Your passwords do not match.");
        return false;
    }
    
    theForm.submit();   
}

function submitSetupForm() {
    var theForm = document.forms["form1"];
    theForm.submit();    
}

function clearJobPosition(job_index) {
    showCompanySearchForJob(job_index);

    var company_id = getElem("company_id_" + job_index);
    if (company_id != null) {
        company_id.value = "";
    }
    var company_name = getElem("company_name_" + job_index);
    if (company_name != null) {
        company_name.value = "";
        j(company_name).show();
    }
    var add_company_text = getElem("add_company_text_" + job_index);
    if (add_company_text != null) {
        add_company_text.value = "";
    }
    
    var job_title = getElem("job_title_" + job_index);
    if (job_title != null) {
        job_title.value = "";
    }
    
    
    for (var i=0; i<document.form1.elements.length; i++) {
        var parts = document.form1.elements[i].id.split("_");
        if (parts[parts.length-1] == job_index && document.form1.elements[i].type=="checkbox") {
            document.form1.elements[i].checked=false;
        }
    }
    
    if (job_index > 1) {
        var job = getElem("job_" + job_index);
        if (job != null) {
            j(job).hide();
        }
        
    }
    var add = getElem("add_" + job_index);
    if (add != null) {
        j(add).show();
    }
}

function toggleNavPromotion(id) {
    var bubbles = ["tracker", "profile", "connect", "settings", "message"];
    for (b in bubbles) {
        if (id != bubbles[b] + "_promotion_nav_bubble") {
            var n = getElem(bubbles[b] + "_promotion_nav_bubble");
            if (n != null) {
                n.style.display = "none";
            }
        }
    }
    var node = getElem(id);
    if (node != null) {
        if (node.style.display != "none") {
            node.style.display = "none";
        } else {
            node.style.display = "block";
        }
    }
}

function sendInvitations() {
    var theForm = document.forms["import_contacts_form"];
    var elem = theForm.elements;
    
    var num_emails = 0;
    for (var i = 0; i < elem.length; i++) {
        if (elem[i].type == "checkbox" && elem[i].checked && elem[i].name != "rakedinemail_checkall" && elem[i].name != "gmailemail_checkall") {
            num_emails += 1;
        }
    }

    if (num_emails > 0) {
        var si = window.confirm("We are about to send email invitations to " + num_emails + " contact(s). Would you like to continue?");
        if (!si) {
            return;
        }
        
        theForm.submit();
    } else {
        alert("Please check at least one contact to invite.");
    }
    
}

function submitProfile() {
    var theForm = document.forms["form1"];
    var message = getElem("message_to_user");
    
    // validate first name
    var fn = getElem("first_name");
    if (fn != null) {
        var first_name = theForm.first_name.value;
        if (trim(first_name).length == 0) {
            alert("Your first name cannot be blank.");
            return false;
        }
    }
    
    // validate last name
    var ln = getElem("last_name");
    if (ln != null) {
        var last_name = theForm.last_name.value;
        if (trim(last_name).length == 0) {
            alert("Your last name cannot be blank.");
            return false;
        }
    }


    for (var i=1; i <= MAX_USER_ROLES; i++) {
        var haveCompany = false;
        var haveJobTitle = false;
        var company_id = getElem("company_id_" + i);
        if (company_id != null && company_id.value != "") {
            haveCompany = true;
        }
        var company_name = getElem("add_company_text_" + i);
        if (company_name != null && company_name.value != "") {
            haveCompany = true;
        }
        var job_title = getElem("job_title_" + i);
        if (job_title != null && job_title.value != "") {
            haveJobTitle = true;
        }
                
        if ((haveCompany && !haveJobTitle) || (!haveCompany && haveJobTitle)) {
            var job = getElem("job_box_" + i);
            if (job != null) {
                job.style.backgroundColor = "#FFEEEE";
            }

            alert("Job position #" + i + " requires both a company and a job title. Either remove it or fill in both fields");            
            return;
        }
    }
    
    if (message != null) {
        message.style.display = "block";
        message.className = "wait";
        message.innerHTML = "Saving...";
    }
    theForm.submit();
}

function submitPassword() {
    var theForm = document.forms["form1"];
    
    var password = theForm.password.value;
    if (password.length == 0) {
        alert("Your password cannot be blank.");
        return false;
    }
    
    var new_password = theForm.new_password.value;
    if (new_password.length == 0) {
        alert("Your new password cannot be blank.");
        return false;
    }
    
    if (new_password.length < 3) {
        alert("Your new password must be at least 3 characters.");
        return false;
    }
    
    var repeat_new_password = theForm.repeat_new_password.value;
    if (new_password != repeat_new_password) {
        alert("Your new passwords do not match.");
        return false;
    }
    
    var error_message = getElem("error_message");
    if (error_message != null) {
        error_message.style.display = "none";
    }
    submitProfile();
}

function registerUser() {
    var theForm = document.forms["form1"];
    
    // validate email
    var emailInput = theForm.email;
    if (emailInput != null && !emailInput.value.match(email_re)) {
        alert("'" + emailInput.value + "' is not a valid email address.");
        return false;
    }
    
    // validate first name
    var first_name = theForm.first_name.value;
    if (first_name.length == 0) {
        alert("Your first name cannot be blank.");
        return false;
    }
    
    // validate last name
    var last_name = theForm.last_name.value;
    if (last_name.length == 0) {
        alert("Your last name cannot be blank.");
        return false;
    }
    
    // validate username
    var username = theForm.username.value;
    if (username.length < 3 || username.length > 20) {
        alert("Your username must be between 3 and 20 characters.");
        return false;
    }
    
    if (!username.match(username_re)) {
        alert("Your username must be contain only the following characters: A-Z, a-z, 0-9, or underscores.");
        return false;
    }
    
    // validate passwords
    var password = theForm.password.value;
    var repeat_password = theForm.repeat_password.value;
    if (password.length == 0) {
        alert("Your password cannot be blank.");
        return false;
    }
    
    if (password.length < 3) {
        alert("Your password must be at least 3 characters.");
        return false;
    }
    
    if (password != repeat_password) {
        alert("Your passwords do not match.");
        return false;
    }
    
    var postal_code = theForm.postal_code;
    if (postal_code.value == "") {
        alert("Postal code cannot be blank.");
        return false;
    }
    
    var industry = theForm.industry;
    if (industry.value == -1 ) {
        alert("Please choose an industry with which you are associated.");
        return false;
    }
    
    theForm.submit();
}


function requireAttributes() {
    var theForm = document.forms["form1"];
    
    // validate first name
    var first_name = theForm.first_name.value;
    if (first_name.length == 0) {
        alert("Your first name cannot be blank.");
        return false;
    }
    
    // validate last name
    var last_name = theForm.last_name.value;
    if (last_name.length == 0) {
        alert("Your last name cannot be blank.");
        return false;
    }
    
    // validate username
    var user_name = theForm.user_name.value;
    if (user_name.length < 3 || user_name.length > 20) {
        alert("Your username must be between 3 and 20 characters.");
        return false;
    }
    
    
    if (!user_name.match(username_re)) {
        alert("Your username must be contain only the following characters: A-Z, a-z, 0-9, or underscores.");
        return false;
    }

    var industry = theForm.industry;
    if (industry.value == -1 ) {
        alert("Please choose an industry with which you are associated.");
        return false;
    }
    
    theForm.submit();
}

function hideTooltipHelper(tooltip_name) {
    var tooltip = getElem(tooltip_name);
    if (tooltip != null) {
        j(tooltip).fadeOut(250);
    }

    var url = "/account/hide_tooltip";
    j.ajax({
        type: "POST",
        url: url,
        data: {tooltip_name:tooltip_name}, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
            }
   });

}

function sendEmailInvites() {
    var theForm = document.forms["invite_contacts_form"];
    
    // validate email
    var emailInput = theForm.invite_contacts_email;
    if (emailInput != null) {
        var emails_list = emailInput.value.split(",");
        if (emails_list.length > 50) {
            alert("You cannot specify more than 50 email addresses.");
            return;
        }
        for (var i=0; i < emails_list.length; i++) {
            if (trim(emails_list[i]) != "") {
                if (!(trim(emails_list[i])).match(email_re)) {
                    alert("'" + emails_list[i] + "' is not a valid email address.");
                    return;
                }                
            }
        }
    }
    
    theForm.submit();

}


function toggleIndustryDropdown() {
    var link = getElem("industry_select_link");
    if (link != null) {
        j("#industry_select_link").toggle();
    }
    var dropdown = getElem("industry_select_dropdown");
    if (dropdown != null) {
        j("#industry_select_dropdown").toggle();
    }
}

function filterFeedsByIndustry() {

    var industry_select = getElem("industry_select");
    if (industry_select != null) {
        var industry_title = getElem("recent_mi_feed_industry");
        if (industry_title != null) {
            var industry_name = industry_select.options[industry_select.selectedIndex].text;
            industry_title.innerHTML = industry_name;
        }
        if (parseInt(industry_select.value) > 0)
            industry_list = industry_select.value;
        else
            industry_list = "";
        setTimeout(function() {refreshFeeds(global_timestamp, global_boa, false, false, source_type, industry_list, "replace");}, 0);            
    }
}

function editIndustries(watchlist_id) {
    var sharing = getElem("edit_watchlist_sharing_" + watchlist_id);
    if (sharing != null) {
        j(sharing).hide();
    }

    var myIndustries = getElem("watchlist_data");
    if (myIndustries != null) {
        //j("#watchlist_data").toggle();
    }
    
    var options = getElem("watchlist_options_links_" + watchlist_id);
    if (options != null) {
        j(options).hide();
    }

    var allIndustries = getElem("all_industries_" + watchlist_id);
    if (allIndustries != null) {
        j(allIndustries).toggle();
        adjustWatchlistHeight();
    }

    var large_add_button = getElem("large_add_button_" + watchlist_id);
    if (large_add_button != null) {
        j(large_add_button).toggle();
    }
}

function updateCompanyList(c_list, watchlist_id) {
    if (personalize_firehose)
        c_list_dict[watchlist_id] = c_list;
}

function updatePersonList(p_list, watchlist_id) {
    if (personalize_firehose)
        p_list_dict[watchlist_id] = p_list;
}

function updateIndustries(ind_list, async, watchlist_id) {
    //doRefreshIndustryMarkets(asyncTimers['industry_markets']);
    if (personalize_firehose) 
        i_list_dict[watchlist_id] = ind_list;

    /*    
    if (! industry_override) {
        industry_list = ind_list;
        var industry_filter_cb = getElem("industry_filter_cb");
        if (async && industry_filter_cb != null && industry_filter_cb.checked) {
            setTimeout(function() {refreshFeeds(global_timestamp, global_boa, false, false, source_type, industry_list, "replace");}, 250);            
        }        
    }
    */
}

function saveIndustries(watchlist_id) {
    var theForm = document.forms["industries_form_" + watchlist_id];
    theForm.save.disabled = true;
    theForm.save.value = "Saving...";
    
    var elem = theForm.elements;
    
    var params = "watchlist_id=" + watchlist_id;
    for (var i = 0; i < elem.length; i++) {
        if (elem[i].type == "checkbox" && elem[i].checked) {
            if (params != "")
                params += "&";

            params += elem[i].name + "=on";
        }
    }

    var header = getElem("firehose_header");
    var headertext = getElem("firehose_headertext");
    if (params != "") {
        var industry_filter_cb = getElem("industry_filter_cb");
        if (industry_filter_cb != null) {
            industry_filter_cb.checked = true;
        }
        var cb = getElem("industry_filter_cb");
        if (cb != null) {
            cb.disabled = false;
        }
        var filterLabel = getElem("filterIndustryLabel");
        if (filterLabel != null) {
            filterLabel.className = "";
        }
        setCookie("recentFeeds_personalizeFH", "checked", 10000);
        if (header != null) {
            header.className = "sb_header sb_header_personal";
        }
        if (headertext != null) {
            headertext.className = "sb_headertext sb_headertext_personal";
            headertext.innerHTML = "My&nbsp;Headlines";
        }
    } else {
        var cb = getElem("industry_filter_cb");
        if (cb != null) {
            cb.disabled = true;
        }
        var filterLabel = getElem("filterIndustryLabel");
        if (filterLabel != null) {
            filterLabel.className = "disabled";
        }
        setCookie("recentFeeds_personalizeFH", "unchecked", 10000);
        if (header != null) {
            header.className = "sb_header";
        }
        if (headertext != null) {
            headertext.className = "sb_headertext";
            headertext.innerHTML = "All&nbsp;Headlines";
        }
    }
    
    var url = "/tracker/save_industries";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data) {
                    var entity_watchlist = getElem("my_watchlist_section_" + watchlist_id);
                    if (entity_watchlist != null) {
                        entity_watchlist.innerHTML = data;
                        adjustWatchlistHeight();
                    }
                    theForm.save.disabled = false;
                    theForm.save.value = "Save";

                    /*
                    var alert = getElem("tracker_changed_alert");
                    if (alert != null)
                        j(alert).show();
                    */
                    var earlier_tracked_items = getElem("earlier_tracked_items");
                    if (earlier_tracked_items != null) {
                        filterTrackedItems();
                    }
                }
            }
   });
    
}

function toggleRecentTrack(type, uri) {
    var trackLink = getElem("recent_" + type + "_" + uri);
    if (trackLink != null) {
        j(trackLink).toggle();
    }
}

function hideVisibleOverlay() {
    if (visibleOverlayContentId != null) {
        var content = getElem(visibleOverlayContentId);
        if (content != null) {
            content.style.top = "-35px";
        }
    }

    j("#" + visibleOverlayId).hide();
    visibleOverlayId = null;
    visibleOverlayContentId = null;
}

function toggleWatchlistInfo(entity_type, entity_uri, watchlist_id) {
    var info = getElem("info_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
    if (info != null) {
        if (!(j.browser.msie && j.browser.version == "6.0"))
            j(info).toggle();
        
    }
    var del = getElem("remove_tracker_link_loading_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
    if (del != null && ("" + del.src).indexOf("icon_trash.gif") >= 0) {
        j(del).toggle();
    }
}

function toggleWatchlistOverlay(entity_type, entity_uri, entity_id, entity_name, entity_ticker, chart_url, chart_width, chart_height) {
    
    var overlay = getElem("watchlist_overlay_" + entity_type + "_" + entity_uri);
    if (overlay != null) {
        
        if (visibleOverlayId != null) {
            if (visibleOverlayId == "watchlist_overlay_" + entity_type + "_" + entity_uri) {
                hideVisibleOverlay();
                return false;
            } else {
                hideVisibleOverlay();
            }
        }
        j("#watchlist_overlay_" + entity_type + "_" + entity_uri).show();
        
        visibleOverlayId = "watchlist_overlay_" + entity_type + "_" + entity_uri;
        visibleOverlayContentId = "watchlist_overlay_content_" + entity_type + "_" + entity_uri;
        
        if (entity_ticker != null) {
            var overlay_chart = getElem("watchlist_overlay_chart_" + entity_type + "_" + entity_uri);
            if (overlay_chart != null) {
                var url = chart_url.replace("[TICKER]", entity_ticker).replace("[HEIGHT]", chart_height).replace("[WIDTH]", chart_width);
                overlay_chart.src = url;
            }
        }
        
        var loading = getElem("loading_overlay_headlines_" + entity_type + "_" + entity_uri);
        if (loading != null) {
            j("#loading_overlay_headlines_" + entity_type + "_" + entity_uri).show();
        }

        var overlay_headlines = getElem("watchlist_overlay_headlines_" + entity_type + "_" + entity_uri);
        if (overlay_headlines != null) {
            j("#watchlist_overlay_headlines_" + entity_type + "_" + entity_uri).hide();
            
            var content = getElem("watchlist_overlay_content_" + entity_type + "_" + entity_uri);
            var pointer = getElem("watchlist_overlay_pointer_" + entity_type + "_" + entity_uri);
            adjustVerticalPosition(content);
            adjustHorizontalPosition(content, pointer);
            
            setTimeout(function() {
                if (visibleOverlayId != "watchlist_overlay_" + entity_type + "_" + entity_uri) {
                    return;
                }
                
                j.ajax({
                    type: "GET",
                    url: "/feed/latest?t=" + entity_type + "&i=" + entity_id + "&n=" + entity_name + "&u=" + entity_uri,
                    cache: false,
                    error:
                        function() {
                            overlay_headlines.innerHTML = "Could not load latest headlines.";
                        },
                    success:
                        function(data){
                            var loading = getElem("loading_overlay_headlines_" + entity_type + "_" + entity_uri);
                            if (loading != null) {
                                j("#loading_overlay_headlines_" + entity_type + "_" + entity_uri).hide();
                            }
                            j("#watchlist_overlay_headlines_" + entity_type + "_" + entity_uri).show();
                            overlay_headlines.innerHTML = data;
                            
                            var content = getElem("watchlist_overlay_content_" + entity_type + "_" + entity_uri);
                            var pointer = getElem("watchlist_overlay_pointer_" + entity_type + "_" + entity_uri);
                            adjustVerticalPosition(content);
                            adjustHorizontalPosition(content, pointer);
                        }
                });                
            }, 100);
        }
    }
}


function adjustVerticalPosition(content) {
    var st = 0;
    var sb = 0;
    st = j(window).scrollTop();

    var corner_content = getElem("tracker_content");
    if (corner_content != null) {
        st += j("#tracker_content").scrollTop() + 40;
        sb = 40;
    }
    
    if (content != null) {
        var wHeight = j(window).height();
        var pos = findPos(content);
        //alert(wHeight + " " + pos[0] + " " + pos[1] + " " + content.offsetHeight + " " + content.style.top);
        if (wHeight < content.offsetHeight + sb + pos[1] - st) {
            if (content.style.top == "" || content.style.top == null) {
                var top = pos[1] - findPos(getElem(visibleOverlayId))[1];
                content.style.top = (parseInt(top -5 + wHeight - (content.offsetHeight + sb + pos[1] - st))) + "px";                      
            } else {
                content.style.top = (parseInt(content.style.top.replace(/px/g, ""))
                + parseInt(-5 + wHeight - (content.offsetHeight + sb + pos[1] - st))) + "px";                      
            }                        
        } else if (pos[1] < 0 + st) {
            content.style.top = "-5px";                      
        }
    }
}


function adjustHorizontalPosition(content, pointer) {
    if (content != null) {
        var pos = findPos(content);
        if (true) { //(pos[0] < 0) {
            content.style.right = "-340px";
            pointer.style.right = "-34px";
            pointer.src = pointer.src.replace(/pointer_right.gif/g, "pointer_left.gif");
        }
    }
}


function showPersonalizationLink() {
    var link = getElem("personalize_tracking_link");
    if (link != null) {
        j(link).show();
    }
}

function getPosition(el) {
   if ('undefined' != typeof( el.offsetParent ) ){  
      for( var x = 0, y =0, sX = 0, sY = 0; el; el = el.offsetParent ){
         sX = el.scrollLeft ? el.scrollLeft : 0;

         sY = el.scrollTop ? el.scrollTop : 0;
         x += el.offsetLeft - sX;
         y += el.offsetTop - sY;
      }
      return [ x, y ];
   } else {  
      //there is no offsetParent here so just
      //send back the elements position
      return [ el.x, el.y ];
   }
}


function findPos(el) {
    var curLeft = 0;
    var curTop = 0;
    if (el.offsetParent) {
        do {
            curLeft += el.offsetLeft;
            curTop += el.offsetTop;
        } while (el = el.offsetParent);
    }
    
    return [curLeft, curTop];
}

// submit the email to us
function submitFeedback() {
   var theForm = document.forms["form1"];
   var elements = new Object()
   
   for (var i=0; i < theForm.elements.length; i++) {
      var alertText = ""
      alertText += "Element Type: " + theForm.elements[i].type + "\n"
      
      if(theForm.elements[i].type == "text" || theForm.elements[i].type == "textarea"){
         alertText += "Element Value: " + theForm.elements[i].value + "\n"
         elements[theForm.elements[i].name] = theForm.elements[i].value;
      }
      else if(theForm.elements[i].type == "checkbox"){
         alertText += "Element Checked? " + theForm.elements[i].checked + "\n"
         elements[theForm.elements[i].name] = theForm.elements[i].checked;
      }
      else if(theForm.elements[i].type == "select-one"){
         alertText += "Selected Option's Text: " + theForm.elements[i].options[theForm.elements[i].selectedIndex].text + "\n"
         elements[theForm.elements[i].name] = theForm.elements[i].options[theForm.elements[i].selectedIndex].text;
      }
      else if(theForm.elements[i].type == "radio" && theForm.elements[i].checked){
         alertText += "Radio Button Selected: " + getCheckedValue(theForm.elements[i]) + "\n"
         elements[theForm.elements[i].name] = getCheckedValue(theForm.elements[i]);
      }
      //alert(alertText)
   }
   var submit = document.getElementById("formsubmit");
   var thanks = document.getElementById("formthanks");

   submit.style.display = "none";
   thanks.style.display = "block";
   
   j.post("/feedback/submit/", elements,
      function(data){
           if (data > 0)
               thanks.innerHTML = "Feedback Sent. Thanks!";
           else {
               thanks.className = "error";
               thanks.innerHTML = "Hmmm. Something went wrong. Please submit again."
           }
           setTimeout(function() {
               j.closeDialog();
           }, 100);
      });
}



// submit the email to us
function submitContactUs() {
   var name_value = document.forms['form1'].elements['name'].value;
   var email_value = document.forms['form1'].elements['email'].value;
   var regarding_value = document.forms['form1'].elements['regarding'].value;
   var body_value = document.forms['form1'].elements['body'].value;

   var submit = document.getElementById("formsubmit");
   var thanks = document.getElementById("formthanks");

   submit.style.display = "none";
   thanks.style.display = "block";
   
   j.post("/contactus/submit/", {name:name_value, email:email_value, regarding:regarding_value, body:body_value},
      function(data){
           if (data > 0)
               thanks.innerHTML = "Your Message was Submitted.";
           else {
               thanks.className = "error";
               thanks.innerHTML = "Hmmm. Something went wrong. Please submit again."
           }
           setTimeout(function() {
               j.closeDialog();
           }, 100);
      });
}

// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function toggleFirehoseFilter() {
    var filter = getElem("firehose_filter");
    if (filter != null) {
        j("#firehose_filter").toggle();
    }

    if (filter.style.display != "none") {
        var link = getElem("firehose_filter_link_tab");
        if (link != null) {
            link.className = "firehose_filter_link_tab";
        }
    } else {
        var link = getElem("firehose_filter_link_tab");
        if (link != null) {
            link.className = "novisited emkcart";
        }

    }
/*
    var filter_link = getElem("firehose_filter_link");
    if (filter_link != null) {
        j("#firehose_filter_link").toggle();
    }
*/
}



function saveFirehoseFilterOptions() {
    var tracker_filter_selected = false;
    var cb = getElem("my_companies_cb");
    if (cb != null && personalize_firehose) {
        if(cb.checked) {
            tracker_filter_selected = true;
            setCookie("fh_filter_tracker_companies", "checked", 10000);
        } else {
            setCookie("fh_filter_tracker_companies", "", 10000);
        }
    }

    cb = getElem("my_people_cb");
    if (cb != null && personalize_firehose) {
        if(cb.checked) {
            tracker_filter_selected = true;
            setCookie("fh_filter_tracker_people", "checked", 10000);
        } else {
            setCookie("fh_filter_tracker_people", "", 10000);
        }
    }

    cb = getElem("my_industries_cb");
    if (cb != null) {
        if(cb.checked && personalize_firehose) {
            tracker_filter_selected = true;
            setCookie("fh_filter_tracker_industries", "checked", 10000);
        } else {
            setCookie("fh_filter_tracker_industries", "", 10000);
        }
    }
    
    var c = ""
    if (document.firehoseFilterForm.filter_tracker != null && personalize_firehose) {
        for (i=0;i<document.firehoseFilterForm.filter_tracker.length;i++) {
            if (document.firehoseFilterForm.filter_tracker[i].checked)  {
                if (document.firehoseFilterForm.filter_tracker[i].value == "filter")
                    c = "checked"
            }
        }
        setCookie("fh_filter_tracker", c, 10000);
        if (!tracker_filter_selected && c == "checked") {
            var select_one = getElem("select_one_tracker");
            if (select_one != null) {
                j(select_one).show();
            }
            return;
        }
    }
    
    var source_filter_selected = false;
    source_types = ""
    var cb = getElem("news_type_cb");
    if (personalize_firehose) {
        if (cb != null && cb.checked) {
            source_filter_selected = true;
            setCookie("fh_filter_sources_news", "checked", 10000);
        } else {
            setCookie("fh_filter_sources_news", "", 10000);
        }        
    } else {
        if  (cb != null && cb.checked) {
            source_filter_selected = true;
            source_types += "news";
        } 
    }

    cb = getElem("press_type_cb");
    if (personalize_firehose) {
        if (cb != null && cb.checked) {
            source_filter_selected = true;
            setCookie("fh_filter_sources_press", "checked", 10000);
        } else {
            setCookie("fh_filter_sources_press", "", 10000);
        }
    } else {
        if  (cb != null && cb.checked) {
            if (source_types != "")
                source_types += ","
                
            source_filter_selected = true;
            source_types += "press releases";
        } 
        
    }
    
    cb = getElem("filings_type_cb");
    if (personalize_firehose) {
        if (cb != null && cb.checked) {
            source_filter_selected = true;
            setCookie("fh_filter_sources_filings", "checked", 10000);
        } else {
            setCookie("fh_filter_sources_filings", "", 10000);
        }
    } else {
        if  (cb != null && cb.checked) {
            if (source_types != "")
                source_types += ","
                
            source_filter_selected = true;
            source_types += "filings";
        } 
    }
    
    if (document.firehoseFilterForm.filter_type != null) {
        c = ""
        for (i=0;i<document.firehoseFilterForm.filter_type.length;i++) {
            if (document.firehoseFilterForm.filter_type[i].checked)  {
                if (document.firehoseFilterForm.filter_type[i].value == "filter")
                    c = "checked"
            }
        }
        if (personalize_firehose) {
            setCookie("fh_filter_sources", c, 10000);
            if (!source_filter_selected && c == "checked") {
                var select_one = getElem("select_one_source");
                if (select_one != null) {
                    j(select_one).show();
                }
                return;
            }
        }
        else if (c == "") {
            source_types = "news,press releases,filings";
        }
    }
    
    var industry_filter_cb = getElem("industry_filter_cb");
    var industry_select = getElem("industry_select");
    if (industry_select != null && parseInt(industry_select.value) > 0) {
        feed_industry_list = industry_select.value;
        setCookie("fh_filter_industry", "checked", 10000);
    } else {
        setCookie("fh_filter_industry", "", 10000);
    }
    
    refreshHeadlines(global_timestamp, global_boa, false, false, "replace");
    toggleFirehoseFilter();
    
    var select_one = getElem("select_one_tracker");
    if (select_one != null) {
        j(select_one).hide();
    }

    select_one = getElem("select_one_source");
    if (select_one != null) {
        j(select_one).hide();
    }

}

function trackerFilterSelect(cb, label_id) {
    if (cb != null) {
        var l = getElem(label_id);
        if (cb.checked && l != null) {
            l.className = "filter_firehose_section_selected";
        } else if (!cb.checked && l!= null) {
            l.className = "filter_firehose_section_notselected";
        }
    }
}

function fh_filterSources() {
    var filter_type = "nofilter"
    for (i=0;i<document.firehoseFilterForm.filter_type.length;i++) {
        if (document.firehoseFilterForm.filter_type[i].checked)  {
            filter_type = document.firehoseFilterForm.filter_type[i].value;
        }
    }
    if (filter_type == "nofilter") {
        var news = getElem("news_type_cb");
        if (news != null) {
            news.disabled = true;
        }
        var press = getElem("press_type_cb");
        if (press != null) {
            press.disabled = true;
        }
        var filings = getElem("filings_type_cb");
        if (filings != null) {
            filings.disabled = true;
        }
        
        var news_text = getElem("news_cb_label");
        if (news_text != null) {
            news_text.className = "disabled";
        }
        var press_text = getElem("press_cb_label");
        if (press_text != null) {
            press_text.className = "disabled";
        }
        var filings_text = getElem("filings_cb_label");
        if (filings_text != null) {
            filings_text.className = "disabled";
        }
        
        var option = getElem("filter_type_nofilter");
        if (option != null) {
            option.className = "filter_firehose_section_selected";
        }
        option = getElem("filter_type_filter");
        if (option != null) {
            option.className = "filter_firehose_section_notselected";
        }
    } else {
        var news = getElem("news_type_cb");
        if (news != null) {
            news.disabled = false;
        }
        var press = getElem("press_type_cb");
        if (press != null) {
            press.disabled = false;
        }
        var filings = getElem("filings_type_cb");
        if (filings != null) {
            filings.disabled = false;
        }

        var news_text = getElem("news_cb_label");
        if (news_text != null) {
            news_text.className = "";
        }
        var press_text = getElem("press_cb_label");
        if (press_text != null) {
            press_text.className = "";
        }
        var filings_text = getElem("filings_cb_label");
        if (filings_text != null) {
            filings_text.className = "";
        }

        var option = getElem("filter_type_nofilter");
        if (option != null) {
            option.className = "filter_firehose_section_notselected";
        }
        option = getElem("filter_type_filter");
        if (option != null) {
            option.className = "filter_firehose_section_selected";
        }
     }
}


function fh_filterTracker() {
    var filter_type = "nofilter"
    for (i=0;i<document.firehoseFilterForm.filter_tracker.length;i++) {
        if (document.firehoseFilterForm.filter_tracker[i].checked)  {
            filter_type = document.firehoseFilterForm.filter_tracker[i].value;
        }
    }
    if (filter_type == "nofilter") {
        var c = getElem("my_companies_cb");
        if (c != null) {
            c.disabled = true;
        }
        var p = getElem("my_people_cb");
        if (p != null) {
            p.disabled = true;
        }
        var i = getElem("my_industries_cb");
        if (i != null) {
            i.disabled = true;
        }
        
        var c_text = getElem("my_companies_cb_label");
        if (c_text != null) {
            c_text.className = "disabled";
        }
        var p_text = getElem("my_people_cb_label");
        if (p_text != null) {
            p_text.className = "disabled";
        }
        var i_text = getElem("my_industries_cb_label");
        if (i_text != null) {
            i_text.className = "disabled";
        }
        
        var option = getElem("filter_tracker_nofilter");
        if (option != null) {
            option.className = "filter_firehose_section_selected";
        }
        option = getElem("filter_tracker_filter");
        if (option != null) {
            option.className = "filter_firehose_section_notselected";
        }
    } else {
        var c = getElem("my_companies_cb");
        if (c != null) {
            c.disabled = false;
        }
        var p = getElem("my_people_cb");
        if (p != null) {
            p.disabled = false;
        }
        var i = getElem("my_industries_cb");
        if (i != null) {
            i.disabled = false;
        }
        
        var c_text = getElem("my_companies_cb_label");
        if (c_text != null) {
            c_text.className = "";
        }
        var p_text = getElem("my_people_cb_label");
        if (p_text != null) {
            p_text.className = "";
        }
        var i_text = getElem("my_industries_cb_label");
        if (i_text != null) {
            i_text.className = "";
        }
        
        var option = getElem("filter_tracker_nofilter");
        if (option != null) {
            option.className = "filter_firehose_section_notselected";
        }
        option = getElem("filter_tracker_filter");
        if (option != null) {
            option.className = "filter_firehose_section_selected";
        }
     }
}



function personalizeFirehose() {
    var replace = "replace";
    var industry_filter_cb = getElem("industry_filter_cb");
    if (industry_filter_cb != null) {
        var header = getElem("firehose_header");
        var headertext = getElem("firehose_headertext");
        if (industry_filter_cb.checked) {
            setCookie("recentFeeds_personalizeFH", "checked", 10000);
            if (header != null) {
                header.className = "sb_header sb_header_personal";
            }
            if (headertext != null) {
                headertext.className = "sb_headertext sb_headertext_personal";
                headertext.innerHTML = "My&nbsp;Headlines";
            }
            refreshFeeds(global_timestamp, global_boa, false, false, source_type, industry_list, replace);            
        } else {
            setCookie("recentFeeds_personalizeFH", "unchecked", 10000);
            if (header != null) {
                header.className = "sb_header";
            }
            if (headertext != null) {
                headertext.className = "sb_headertext";
                headertext.innerHTML = "All&nbsp;Headlines";
            }
            refreshFeeds(global_timestamp, global_boa, false, false, source_type, "", replace);                        
        }
    }
}


function doCheckForNewFeeds(_sort_by, msec) {
    var sb = sort_by;
    if (_sort_by != null)
        sb = _sort_by;

    if (sb == "date") {
        if (msec == null) {
            msec = asyncRefreshRates['recent_feeds'] + myRand(1,10);    
        }
        clearTimeout(asyncTimers['recent_feeds']);
        asyncTimers['recent_feeds'] = setTimeout("checkForNewFeeds('" + sb + "')", msec);
    }  else {
        if (msec == null) {
            msec = asyncRefreshRates['top_feeds'] + myRand(1,10);
        }
        clearTimeout(asyncTimers['top_feeds']);
        asyncTimers['top_feeds'] = setTimeout("checkForNewFeeds('" + sb + "')", msec);
    }
    
}

function checkForNewFeeds(sb) {
    if (sb=="date" && feed_page != 1) {
        return;
    }
    
    // if we are already doing an ajax or feeds call or if user is inactive, return
    if (!ajaxSemaphoreAvailable || !feedsSemaphoreAvailable || !global_activity) {
        doCheckForNewFeeds(sb, 2000);   
        return;
    }
    
    ajaxSemaphoreAvailable = false;
    
    var timestamp = parseInt(newest_date);
    
    feed_ids = "";
    if (sb=="date") {
       feed_ids = recent_feed_ids;
    } else {
       feed_ids = top_feed_ids;
    }
    
    industries = industry_list;
    var industry_filter_cb = getElem("industry_filter_cb");
    var industry_select = getElem("industry_select");
    if (industry_filter_cb == null || !industry_filter_cb.checked) {
        if (industry_select == null || parseInt(industry_select.value) < 0) {
            industries = "";            
        }
    }
    
    if (industry_override) {
        industries = feed_industry_list;
    }

    var extra = "";
    if (feed_entity_type != null) {
        extra = "&entity_id=" + feed_entity_id + "&entity_type=" + feed_entity_type
    } else if (sb=="date") {
         extra = "&industry_list=" + industries
    }
    
    j.ajax({
       url: "/feed/refresh/?source_type=" + source_type + "&feed_ids=" + feed_ids + "&ts=" + timestamp + "&fs=" + sb + "" + extra,
       cache: false,
       success: function(data) {
          if (data > 0 && feedsSemaphoreAvailable) {
             if (sb=="date") {
                 var msg = getElem("newRecentFeedAlertCount");
                 if (msg != null)
                     msg.innerHTML = data;
     
                 var plural = getElem("newRecentFeedAlertPlural");
                 if (plural != null) {
                    if (data > 1) {
                       plural.innerHTML = "s";
                    } else {
                       plural.innerHTML = "";
                    }                    
                 }

                 setTimeout(function() {

                    j('#loading_recent_feed_alert').hide();    
                    j('#new_recent_feed_alert').show();             
                    j('#tracker_changed_alert').hide();
                 }, 50);
             } else {
                 var msg = getElem("newTopFeedAlertCount");
                 if (msg != null)
                     msg.innerHTML = data;
     
                 var plural = getElem("newTopFeedAlertPlural");
                 if (plural != null) {
                    if (data > 1) {
                       plural.innerHTML = "s";
                    } else {
                       plural.innerHTML = "";
                    }                    
                 }

                 setTimeout(function() {
                     j('#new_top_feed_alert').show();             
                 }, 50);                
             }
          }
          ajaxSemaphoreAvailable = true;
          doCheckForNewFeeds(sb);
       }
    });   
}



function doCheckForNewHeadlines(_sort_by, msec) {
    var sb = sort_by;
    if (_sort_by != null)
        sb = _sort_by;

    if (sb == "date") {
        if (msec == null) {
            msec = asyncRefreshRates['recent_feeds'] + myRand(1,10);    
        }
        clearTimeout(asyncTimers['recent_feeds']);
        asyncTimers['recent_feeds'] = setTimeout("checkForNewHeadlines('" + sb + "')", msec);
    }  else {
        if (msec == null) {
            msec = asyncRefreshRates['top_feeds'] + myRand(1,10);
        }
        clearTimeout(asyncTimers['top_feeds']);
        asyncTimers['top_feeds'] = setTimeout("checkForNewHeadlines('" + sb + "')", msec);
    }
    
}

function checkForNewHeadlines(sb) {
    if (sb=="date" && feed_page != 1) {
        return;
    }
    
    // if we are already doing an ajax or feeds call or if user is inactive, return
    if (!ajaxSemaphoreAvailable || !feedsSemaphoreAvailable || !global_activity) {
        doCheckForNewHeadlines(sb, 2000);   
        return;
    }
    
    ajaxSemaphoreAvailable = false;
    
    var timestamp = parseInt(newest_date);
    
    feed_ids = "";
    if (sb=="date") {
       feed_ids = newest_feed_ids;
    } else {
       feed_ids = top_feed_ids;
    }
    
    var industry_filter_cb = getElem("industry_filter_cb");

    user_id_filter = user_id_tracker_shown;
    
    feed_company_list = "";
    for (c in c_list_dict) {
        feed_company_list += c_list_dict[c] + ","
    }
    if (feed_company_list != "") {
        feed_company_list = feed_company_list.substring(0, feed_company_list.length-1)
    }
    
    feed_person_list = "";
    for (p in p_list_dict) {
        feed_person_list += p_list_dict[p] + ","
    }
    if (feed_person_list != "") {
        feed_person_list = feed_person_list.substring(0, feed_person_list.length-1)
    }
    
    feed_industry_list = "";
    for (i in i_list_dict) {
        feed_industry_list += i_list_dict[i] + ","
    }
    if (feed_industry_list != "") {
        feed_industry_list = feed_industry_list.substring(0, feed_industry_list.length-1)
    }
        
    // get industry from dropdown if it exists
    var industry_select = getElem("industry_select");
    if (feed_industry_list == "" && industry_select != null && parseInt(industry_select.value) > 0) {
        feed_industry_list = industry_select.value;
    }

    var url = "/feed/check/?company_list=" + feed_company_list
                        + "&person_list=" + feed_person_list
                        + "&industry_list=" + feed_industry_list
                        + "&profile_id=" + profile_id
                        + "&feed_ids=" + feed_ids
                        + "&ts=" + timestamp
                        + "&fs=" + sb
                        + "&user_id_filter=" + user_id_filter;
    
    if (!personalize_firehose) {
        url += "&source_types=" + source_types;
    }

                        
    j.ajax({
       url: url,
       cache: false,
       success: function(data) {
          if (data > 0 && feedsSemaphoreAvailable) {
             if (sb=="date") {
                 var msg = getElem("newRecentFeedAlertCount");
                 if (msg != null)
                     msg.innerHTML = data;
     
                 var plural = getElem("newRecentFeedAlertPlural");
                 if (plural != null) {
                    if (data > 1) {
                       plural.innerHTML = "s";
                    } else {
                       plural.innerHTML = "";
                    }                    
                 }

                 setTimeout(function() {
                    j('#loading_recent_feed_alert').hide();    
                    j('#new_recent_feed_alert').show();             
                    j('#tracker_changed_alert').hide();
                 }, 50);
             } else {
                 var msg = getElem("newTopFeedAlertCount");
                 if (msg != null)
                     msg.innerHTML = data;
     
                 var plural = getElem("newTopFeedAlertPlural");
                 if (plural != null) {
                    if (data > 1) {
                       plural.innerHTML = "s";
                    } else {
                       plural.innerHTML = "";
                    }                    
                 }

                 setTimeout(function() {
                     j('#new_top_feed_alert').show();             
                 }, 50);                
             }
          }
          ajaxSemaphoreAvailable = true;
          doCheckForNewHeadlines(sb);
       }
    });   
}


function refreshTopIndustryFeed(industry_id, industry_uri) {
    // if we are already doing an ajax or feeds call or if user is inactive, return
    if (!ajaxSemaphoreAvailable || !feedsSemaphoreAvailable || !global_activity) {
       return;
    }
    
    ajaxSemaphoreAvailable = false;
    j.ajax({
       url: "/feed/single/?source_type=news&industry_id=" + industry_id + "&industry_uri=" + industry_uri,
       cache: false,
       success: function(data) {
          if (data) {
            dataArray = data.split("<!-- delimiter -->");
            currentFeedId = getElem("top_industry_feed_id_" + industry_id);
            if (currentFeedId != null && dataArray.length == 2) {
                if (dataArray[0] != currentFeedId.value) {
                    currentFeedId.value = dataArray[0];
                    topStory = getElem("top_industry_feed_" + industry_id);
                    if (topStory != null) {
                        j("#top_industry_feed_" + industry_id).fadeOut(250);
                        setTimeout(function() {
                            topStory.innerHTML = dataArray[1];
                            j("#top_industry_feed_" + industry_id).fadeIn(500);
                        }, 270);
                    }
                }
            }
          }
          ajaxSemaphoreAvailable = true;
       }
    });       
}


function refreshAllTopIndustryFeeds() {
    // if we are already doing an ajax or feeds call or if user is inactive, return
    if (!ajaxSemaphoreAvailable || !feedsSemaphoreAvailable || !global_activity) {
        //setTimeout("refreshAllTopIndustryFeeds()", 2000)
        return;
    }
    
    ajaxSemaphoreAvailable = false;
    j.ajax({
        url: "/feed/industries/?source_type=news",
        cache: false,
        success: function(data) {
            if (data) {
                masterDataArray = data.split("<!-- industry delimiter -->");
                for (var i=0; i < masterDataArray.length; i++) {
                    dataArray = masterDataArray[i].split("<!-- delimiter -->");
                    if (dataArray.length >= 3) {
                        var feedId = trim(dataArray[0]);
                        var industryId = trim(dataArray[1]);
                        var topStoryHTML = trim(dataArray[2]);
                        var theCount = trim(dataArray[3]);
                        var topStory = getElem("top_industry_feed_" + industryId);
                        if (topStory != null) {
                            //j("#top_industry_feed_" + industryId).hide();
                            //setTimeout(function() {
                            topStory.innerHTML = topStoryHTML;
                            //j("#top_industry_feed_" + industryId).fadeIn(500);
                            //}, 270);
                        }
                        
                        var numStories = getElem("industry_feed_count_" + industryId);
                        if (numStories != null) {
                            numStories.innerHTML = theCount;
                        }
                    }
                }
            }
            ajaxSemaphoreAvailable = true;
        }
    });       
}



function cancelNewFeedsMsg() {
   j('#new_recent_feed_alert').fadeOut(250);
}

function refreshMarketChart(url) {
    var now = new Date();
    var img = getElem("market_img");
    if (img != null) {
        img.src = url + "-I=" + now.getSeconds();
    }
}

function popoutWatchlist() {
    /*
    var openOrClosed = getCookie("cornerWatchlist_openOrClosed");
    if (openOrClosed == "open") {
        toggleWatchlistCorner(false);
    }
    */
    if (popoutWindow != null) {
        popoutWindow.close();
    }
    popoutWindow = window.open('/tracker','tracker','width=600,height=600,resizable=1,scrollbars=1,toolbar=0,location=0,directories=0,status=0,menubar=0,copyhistory=0');
}


function toggleWatchlistDock(animate) {
    var corner = getElem("watchlist_dock");
    var corner_link = getElem("fixedcorner_link");
    if (corner != null && corner_link != null) {
        if (corner.style.display == "block") {
            setCookie("cornerWatchlist_openOrClosed", "closed", 10000);
        } else {
            setCookie("cornerWatchlist_openOrClosed", "open", 10000);
        }

        if (animate != null && animate)
            if (corner_link.style.display == "none") {
                j("#watchlist_dock").slideToggle(250, function() {j("#fixedcorner_link").toggle();});                       
            } else {
                j("#fixedcorner_link").toggle(10, function() {j("#watchlist_dock").slideToggle(300)});       
            }
        else {
            j("#fixedcorner_link").toggle();
            j("#watchlist_dock").toggle();
        }            
    }
}


function toggleWatchlistCorner(animate) {
    var corner = getElem("ticker_watchlist_corner");
    var corner_link = getElem("fixedcorner_link");
    if (corner != null) {
        if (corner.style.display == "block") {
            setCookie("cornerWatchlist_openOrClosed", "closed", 10000);
        } else {
            setCookie("cornerWatchlist_openOrClosed", "open", 10000);
        }

        if (animate != null && animate)
            if (corner_link != null && corner_link.style.display == "none") {
                j("#ticker_watchlist_corner").toggle();
                if (corner_link != null) {
                    j("#fixedcorner_link").toggle();                    
                }
            } else {
                if (corner_link != null) {
                    j("#fixedcorner_link").toggle();                    
                }
                j("#ticker_watchlist_corner").toggle();    
            }
        else {
            if (corner_link != null) {
                j("#fixedcorner_link").toggle();                    
            }
            j("#ticker_watchlist_corner").toggle();
        }            
    }
    
    var tracker_nav_link = getElem("tracker_nav_link");
    if (tracker_nav_link != null) {
        if (corner.style.display == "none") {
            tracker_nav_link.className = "tracker_nav_link_unselected";
        } else {
            tracker_nav_link.className = "tracker_nav_link_selected";
        }        
    }
    
    adjustWatchlistHeight();
}

function closeTracker() {
    var corner = getElem("ticker_watchlist_corner");
    setCookie("cornerWatchlist_openOrClosed", "closed", 10000);
    j("#ticker_watchlist_corner").hide();
    var tracker_nav_link = getElem("tracker_nav_link");
    if (tracker_nav_link != null) {
            tracker_nav_link.className = "tracker_nav_link_unselected";
    }
}


function adjustWatchlistHeight() {
    // we don't use this anymore    
    return;

    var corner_content = getElem("tracker_content");
    var corner_content_2 = getElem("tracker_content_2");
    var corner = getElem("ticker_watchlist_corner");
    if (corner_content != null && corner_content_2 != null && (corner == null || corner.style.display != "none")) {
        if (j(window).height() - 75 < j("#tracker_content_2").height()) {
            var newHeight = parseInt(j(window).height() - 75);
            if (newHeight < 300) {
                newHeight = 300;
            }
            corner_content.style.height = newHeight + "px";                    
        } else if (j("#tracker_content_2").height() < j(window).height() - 75) {
            corner_content.style.height = "";                    
        }
    }
}


function resetWatchlistCornerLocation() {
    var corner = getElem("ticker_watchlist_corner");
    if (corner != null) {
        j("#ticker_watchlist_corner").draggable('destroy');
        j("#ticker_watchlist_corner").draggable('enable');
    }
}

function reverse_string(str) {
   var retVal = "";
   var i=str.length - 1;
   
   for (var x = i; x >=0; x--) {
      retVal += str.charAt(x);
   }
   
   return retVal;
}

function doTaggeration(etype, eid) {
    var description = getElem("entity_desc_text_full_content");
    
    if (description != null) {
        j.post("/utility/taggerate/", {etype:etype, eid:eid},
           function(data){
                if (data != 0) {
                    var node = getElem("entity_description");
                    if (node != null) {
                        node.innerHTML = data;
                        if (global_description_toggle == "more") {
                            toggleEntityDescription("more");
                        }
                    }
                }
           });
        
    }
}

function doUserTaggeration(user_id) {
    var description = getElem("entity_desc_text_full_content");
    
    if (description != null) {
        j.post("/utility/taggerate_user_bio/", {user_id:user_id},
           function(data){
                if (data != 0) {
                    var node = getElem("user_bio_section");
                    if (node != null) {
                        node.innerHTML = data;
                        if (global_description_toggle == "more") {
                            toggleEntityDescription("more");
                        }
                    }
                }
           });
        
    }
}

function format_number_suffix(number, dec_places) {
   var suffix = ""
   var factor = 1.0
   
   if (dec_places < 0 || dec_places == null) {
      dec_places = 2
   }
   
   // calculate the suffix
   if (number > 1000000000000 || number < -1000000000000) {
      suffix = "T";
      factor = 1000000000000.0;
   } else if (number > 1000000000 || number < -1000000000) {
      suffix = "B";
      factor = 1000000000.0;
   } else if (number > 1000000 || number < -1000000) {
      suffix = "M";
      factor = 1000000.0;
   } else if (number > 1000 || number < -1000) {
      suffix = "K";
      factor = 1000.0;
   }
   
   return format_decimal(number/factor, dec_places) + suffix;
}
    

function format_decimal(perc, dec_places) {
   var retVal = ""
   var temp = ""
   
   if (perc == null) {
      return retVal;
   } else {
      temp = perc.toString()
   }
   
   before_and_after = temp.split('.');
    
   if (before_and_after != null && before_and_after.length > 0)
      retVal = before_and_after[0];
    
   if (before_and_after != null && before_and_after.length > 1 && dec_places > 0)
      retVal += "." + before_and_after[1].substring(0, dec_places);
    
   return retVal
}


function format_number_USA(number, decimal) {
   var sign = "";
      
   numberString = number.toString();
   if (decimal && numberString.indexOf(".") < 0) {
      numberString += ".00";
   }
   
   if (numberString.charAt(0) == "+" || numberString.charAt(0) == "-" ) {
        sign = numberString.charAt(0);
        numberString = numberString.substring(1);
   }
   
   var decimals = numberString.split(".");
   
   var retVal = ""
   var reverse = reverse_string(decimals[0]);

   if (reverse.length > 1) {
      // check for negative
      // for each 3 numbers, throw in a comma
      var i=0;
   
      for (var c=0; c < reverse.length; c++) {
         i+=1
         retVal += reverse.charAt(c)   ;
         //if it's not the beginning of the number, put a comma every 3rd number
         if (i%3==0 && i < reverse.length) {
               retVal += ","
         }
      }
   } else {
      retVal = reverse;
   }
   
   // reverse it back
   retVal = sign + reverse_string(retVal)

   if (decimal) {
      if (decimals[1].length == 0) {
         decimals[1] += "00";
      } else if (decimals[1].length == 1) {
         decimals[1] += "0";
      } else if (decimals[1].length > 2) {
         decimals[1] = decimals[1].substring(0,2);
      }   
      retVal += "." + decimals[1];
   }    
   
   return retVal
}

function format_money_USA(number, decimal) {
   formatted = format_number_USA(number, decimal)

   if (formatted.charAt(0) == "-") {
      return formatted.charAt(0) + "$" + formatted.substring(1, formatted.length);
   }
   return "$" + formatted;
}



function renderHoldingsPieChart(flashFile, xmlFile, loadingImg, width, height) {
   var chartDiv = getElem("holdingschartdiv");
   if (chartDiv != null) {
        chartDiv.className = "chartloading";
        chartDiv.innerHTML = "<img src=\"" + loadingImg + "\"/>";
     
        setTimeout(function() {
           chartDiv.className = "chartloaded";
           var chart = new FusionCharts(flashFile, "HoldingsLine", width, height);
           chart.setDataURL(xmlFile);		   
           chart.render("holdingschartdiv");      
        }, 250);
   }
}


function renderTransactionChart(flashFile, xmlFile, loadingImg, year, ticker) {
   var chartDiv = getElem("transactionchartdiv");
   /*
   chartDiv.className = "chartloading";
   chartDiv.innerHTML = "<img src=\"" + loadingImg + "\"/>";
   */
   if (chartDiv != null) {
        setTimeout(function() {
           //chartDiv.className = "chartloaded";
           var chart = new FusionCharts(flashFile, "TransactionsLine", "600", "300");
           // for some reason, FusionCharts doesn't like multiple GET variables, have to combine them.
           chart.setDataURL(xmlFile + "?vars=" + ticker + "-" + year);
           chart.render("transactionchartdiv");
        }, 250);
   }
}


function setTab(tabId, contentId, tabIds, contentIds) {
   // first unselect all tabs
   var t = null;
   for (tab in tabIds) {
      t = getElem(tabIds[tab]);
      if (t != null) {
         t.className = "tab tab_none";
      }
   }
   
   // also make all contents display:none
   var c = null;
   for (content in contentIds) {
      c = getElem(contentIds[content]);
      if (c != null) {
         c.style.display = "none";
      }
   }
   
   // select the tab
   var tab = getElem(tabId);
   if (tab != null)
      tab.className = "tab tab_block";
   
   // display the content
   var content = getElem(contentId);
   if (content != null)
      content.style.display = "block";      
}

function convertMinutesScale(min) {
   if (min <= 60) {      
      return min/6;
   }
   // for < 30 min ago
   else if (min <= 120) {
      return 10 + (min-60)/3;                
   }
   // for < 60 min ago
   else if (min <= 180) {
      return 30 + (min-120)/2;                
   }
   // for < 2 hours ago
   else if (min <= 240) {
      return 60 + (min-180);                
   }
   // for < 4 hours ago
   else if (min <= 300) {
      return 120 + (min-240)*2;                
   }
   // for < 8 hours ago
   else if (min <= 360) {
      return 240 + (min-300)*4;                
   }
   // for < 12 hours ago
   else if (min <= 420) {
      return 480 + (min-360)*4;  
   }
   // for < 24 hours ago
   else if (min <= 480) {
      return 720 + (min-420)*12;                
   }
   // for < 36 hours ago
   else if (min <= 540) {
      return 1440 + (min-480)*12;
   }
   // for < 48 hours ago
   else if (min <= 600) {
      return 2160 + (min-540)*12;                
   }
   
   return -1
}

function feedSliderDate(numMin) {
   numMin = parseInt(numMin);
   if (numMin == 0) {
      return "Right&nbsp;Now";
   }
   
   if (numMin <= 90) {
      return parseInt(numMin) + "&nbsp;min&nbsp;ago";
   }
   
   if (numMin <= 60*24) {
      var numHours = parseInt(numMin/60);
      var numMin = parseInt(numMin - parseInt(numMin/60)*60);
      return numHours + "&nbsp;hrs" + (numMin>0 ? ",&nbsp;" + numMin + "&nbsp;min" : "") + "&nbsp;ago";
   }
   
   return parseInt(numMin/60) + "&nbsp;hrs&nbsp;ago";
}

function showCompaniesSearch() {
    var watchlist = getElem("watchlist");
    if (watchlist != null) {
        watchlist.style.display = "none";
    }
    
    var companylist = getElem("companylist");
    if (companylist != null) {
        companylist.style.display = "block";
    }
}


function doSearchWatchlist() {
    var q = getElem("search_watchlist_text").value;
    
    var resultsNode = getElem("search_watchlist_results"); 
    if (resultsNode != null) {
        resultsNode.innerHTML = "";
    }
    
    var loadingNode = getElem("search_watchlist_loading");
    if (loadingNode != null) {
        loadingNode.style.display = "block";
    }
    
    j.ajax({
        url: "/search/watchlist/?q=" + q,
        cache:true,
        success:
        function(data){
            if (data) {
                if (loadingNode != null) {
                    loadingNode.style.display = "none";
                }
                
                if (resultsNode != null) {
                    resultsNode.innerHTML = data;                    
                }
            }
        }
    });
}

function doSubmitSearchWatchlist(event) {
   // if return key is pressed
    if (event.keyCode == 13) {
        doSearchWatchlist();
    }
}



function doSearchCompare(entity_type, uri) {
    var q = getElem("search_compare_text").value;
    
    var resultsNode = getElem("search_compare_results"); 
    if (resultsNode != null) {
        resultsNode.innerHTML = "";
    }
    
    var loadingNode = getElem("search_compare_loading");
    if (loadingNode != null) {
        loadingNode.style.display = "block";
    }
    
    j.ajax({
        url: "/search/compare/?q=" + q + "&entity_type=" + entity_type + "&uri=" + uri,
        cache:true,
        success:
        function(data){
            if (data) {
                if (loadingNode != null) {
                    loadingNode.style.display = "none";
                }
                
                if (resultsNode != null) {
                    resultsNode.innerHTML = data;                    
                }
            }
        }
    });
}

function doSubmitSearchCompare(event, entity_type, uri) {
   // if return key is pressed
    if (event.keyCode == 13) {
        doSearchCompare(entity_type, uri);
    }
}

function clickCompareTab(timeString) {
    var times = ["1month", "6month"];
    
    for (i=0; i < times.length; i++) {
        document.getElementById("compare_tab_" + times[i]).style.display = "none";
    }
    document.getElementById("compare_tab_" + timeString).style.display = "block";
    
    for (i=0; i < times.length; i++) {
        document.getElementById("tab_" + times[i]).className = "compare_tab_notselected";
    }
    document.getElementById("tab_" + timeString).className = "compare_tab_selected";
    
}

function toggleFAQ(tag) {
    var answer = document.getElementById(tag + "_answer");
    if (answer) {
        j('#' + tag + "_answer").slideToggle(250);
    }
}

function toggleEntityDescription(more_or_less) {
    global_description_toggle = more_or_less;
    var fullText = document.getElementById("entity_desc_text_full");
    var clippedText = document.getElementById("entity_desc_text");
    var ellipse = document.getElementById("entity_desc_ellipse");
    var moreLink = document.getElementById("entity_desc_more");
    
    if (more_or_less == "more") {
        if (clippedText != null && fullText != null) {
            var temp = clippedText.innerHTML;
            clippedText.innerHTML = fullText.innerHTML;
            fullText.innerHTML = temp;
        }
        
        if (moreLink != null) {
            moreLink.innerHTML = "less";
            moreLink.href="javascript:toggleEntityDescription('less');";
        }

        if (ellipse != null) {
            ellipse.innerHTML = "";
        }        
    } else {
        if (clippedText != null && fullText != null) {
            var temp = fullText.innerHTML;
            fullText.innerHTML = clippedText.innerHTML;
            clippedText.innerHTML = temp;
        }
        
        if (moreLink != null) {
            moreLink.innerHTML = "more";
            moreLink.href="javascript:toggleEntityDescription('more');";
        }        
        
        if (ellipse != null) {
            ellipse.innerHTML = "...";
        }        
    }
}

function toggleUpdatesFilter(id) {
    doHideUpdatesFilters = false;
    
    if (id == "optionsType") {
        j("#optionsJump").hide();
    } else if (id == "optionsJump") {
        j("#optionsType").hide();
    }
    j("#" + id).toggle();
}

function hideUpdatesFilters() {
    if (doHideUpdatesFilters) {
        j("#optionsType").hide();
        j("#optionsJump").hide();
    } else {
        doHideUpdatesFilters = true;
    }
}

function showLeaderboard(day, all_days) {
    var days = all_days.split(",")
    for (var i=0; i < days.length; i++) {
        var d = days[i];
        var d_tab = getElem("leaderboard_tab_" + d);
        if (d_tab != null) {
            if (d == day)
                d_tab.className = "tab tab_block";
            else
                d_tab.className = "tab tab_none";
        }
        
        var d_node = getElem("leaderboard_" + d);
        if (d_node != null) {
            if (d == day)
                d_node.style.display = "block";
            else
                d_node.style.display = "none";
        }
    }
}

function changeMarketChart(zoom, url, index, height) {
    changeChartSizeIndex(url, height, index);
    var intervals = ['dow', 'snp', 'nasdaq', 'compare'];
    
    var tab = null;
    for (var i=0; i < intervals.length; i++) {
        tab = getElem("market_chart_" + intervals[i]);
        if (tab != null) {
            tab.className = "market_tab_not_selected";
        }
    }
    
    tab =  getElem("market_chart_" + zoom);
    if (tab != null) {
        tab.className = "market_tab_selected";
    }
    
    var legend = getElem("market_compare_legend");
    if (legend != null) {
        if (zoom == "compare") {
            legend.style.display = "block";
        } else {
            legend.style.display = "none";
        }
    }
    
}

function changeCompanyChartZoom(zoom, url, ticker, height) {
    changeChartSize(url, ticker, height);
    var intervals = ['1d', '1m', '3m', '6m', '1y', '5y', '10y'];
    
    var tab = null;
    for (var i=0; i < intervals.length; i++) {
        tab = getElem("company_chart_" + intervals[i]);
        if (tab != null) {
            tab.className = "market_tab_not_selected";
        }
    }
    
    tab =  getElem("company_chart_" + zoom);
    if (tab != null) {
        tab.className = "market_tab_selected";
    }
    
    var prev_close = getElem("prev_close");
    if (prev_close != null) {
        if (zoom == "1d") {
            prev_close.style.visibility = "visible";
        } else {
            prev_close.style.visibility = "hidden";
        }
    }
}

function changeChartSize(url, ticker, height) {
    // jquery doesn't like ids with periods, so need to remove periods
    var tickerNoDot = ticker.replace(".","");
    var loading = getElem("market_loading_" + tickerNoDot);
    if (loading != null) {
        j("#market_loading_" + tickerNoDot).fadeIn(100);
        setTimeout(function() { doneLoadingChart(tickerNoDot); }, 5000);
    }
    
    company_market_url = url;

    var newChart = getElem("company_market_chart_" + ticker);
    if (newChart != null) {
        var newChartWidth = newChart.offsetWidth - 15;
        if (newChartWidth > 800) {
            newChartWidth = 800;
        }
        
        var now = new Date();
        var img = getElem("market_img_" + ticker);
        img.width = newChartWidth;
        img.height = height;
        
        var url = url.replace("[TICKER]", ticker).replace("[HEIGHT]", height).replace("[WIDTH]", newChartWidth);
        url += "-I=" + now.getMilliseconds();
        
        if (img != null) {
            img.onload = function() {
                var loading = getElem("market_loading_" + tickerNoDot);
                if (loading != null) {
                    j("#market_loading_" + tickerNoDot).fadeOut(100);
                }
            }
            img.src = url;
        }        
    }
}

function selectTicker(url, ticker, height) {
    if (company_ticker_symbols != null) {
        var nav_item = null;
        for (t in company_ticker_symbols) {
            nav_item = getElem("company_ticker_navitem_" + company_ticker_symbols[t]);
            if (nav_item != null) {
                nav_item.className = "intranav_dark";
            }
        }
        
        nav_item = getElem("company_ticker_navitem_" + ticker);
        if (nav_item != null) {
            nav_item.className = "intranav_dark intranav_dark_selected";
        }

        var content = null;
        for (t in company_ticker_symbols) {
            content = getElem("company_ticker_content_" + company_ticker_symbols[t]);
            if (content != null) {
                j(content).hide();
            }
        }
        
        content = getElem("company_ticker_content_" + ticker);
        if (content != null) {
            j(content).show();
        }
        
        changeChartSize(url, ticker, height);
    }
}
function doneLoadingChart(ticker) {
    var loading = getElem("market_loading_" + ticker);
    if (loading != null) {
        j("#market_loading_" + ticker).fadeOut(100);
    }
}


function doneLoadingMarketChart() {
    var loading = getElem("markets_loading");
    if (loading != null) {
        j("#markets_loading").fadeOut(100);
    }
}

function toggleMoreWatchlistItems(watchlist_id) {
    var inactive = getElem("inactive_items_" + watchlist_id);
    if (inactive != null) {
        j(inactive).toggle();
    }
    var more_link = getElem("more_inactive_link_" + watchlist_id);
    if (more_link != null) {
        j(more_link).toggle();
    }
}

function changeChartSizeFeatured(url, ticker, height) {
    var newChart = getElem("featured_market_chart");
    if (newChart != null) {
        var newChartWidth = 95; //newChart.offsetWidth - 15
        
        var now = new Date();
        var img = getElem("featured_market_img");
        img.width = newChartWidth;
        img.height = height;
        
        var url = url.replace("[TICKER]", ticker).replace("[HEIGHT]", height).replace("[WIDTH]", newChartWidth);
        url += "-I=" + now.getSeconds()
        if (img != null) {
            img.src = url;
        }
    }
}

function changeChartSizeSearch(url, ticker, height) {
    var newChart = getElem("search_market_chart");
    if (newChart != null) {
        var newChartWidth = newChart.offsetWidth - 5;
        
        var now = new Date();
        var img = getElem("search_market_img");
        img.width = newChartWidth;
        img.height = height;
        
        var url = url.replace("[TICKER]", ticker).replace("[HEIGHT]", height).replace("[WIDTH]", newChartWidth);
        url += "-I=" + now.getSeconds()
        
        if (img != null) {
            img.src = url;
        }
    }
}

function changeChartSizeIndex(url, height, index) {
    var loading = getElem("markets_loading");
    if (loading != null) {
        j("#markets_loading").fadeIn(100);
        setTimeout(function() { doneLoadingMarketChart(); }, 5000);
    }
    
    var newChart = getElem("index_market_chart");
    if (newChart != null) {
        var newChartWidth = 250; //newChart.offsetWidth - 15;
        
        index_market_url = url;
        index_market_ticker = index;
        
        var now = new Date();
        var img = getElem("market_img");
        img.width = newChartWidth;
        img.height = height;
        
        var url = url.replace("[HEIGHT]", height).replace("[WIDTH]", newChartWidth).replace("[TICKER]", index);
        url += "-I=" + now.getSeconds()
        
        if (img != null) {
            img.onload = function() {
                var loading = getElem("markets_loading");
                if (loading != null) {
                    j("#markets_loading").fadeOut(100);
                }
            }
            img.src = url;
        }
    }
}

function loadEntities(cookieString) {
    var html = getPortfolioHTML("Recently Visited", cookieString);
    var entities = getElem(cookieString);
    if (entities != null) {
        entities.innerHTML = html.join(" ");
    }
}

function getPortfolioHTML(title, cookieString) {
    var html = new Array();
    
    html[html.length] = "<div class='sb_header'>";
    if (cookieString == "recentEntities")
        html[html.length] = "<a href='javascript:clearRecentEntities();' class='see_more'>clear list</a>";
    
    html[html.length] = "<div class='sb_headertext'>" + title + "</div></div>";
    
    var recentEntities = getCookie(cookieString);
    if (recentEntities != null && recentEntities != "") {
        
        html[html.length] = "<table class='watchlist_table'>";
        html[html.length] = "<thead><tr><th>Entity</th><th>Ticker</th><th class='numerical'>Price</th><th class='numerical'>Change</th></tr></thead>";
        html[html.length] = "<tbody>";
        
        recent_ticker_list[cookieString] = "";
        var entityList = recentEntities.split("|");
        for (var i=0; i < entityList.length && i < 60; i+=4) {
            if (entityList[i] != "") {
                if (recent_ticker_list[cookieString] == "") {
                    recent_ticker_list[cookieString] = entityList[i];                
                } else {
                    recent_ticker_list[cookieString] += "," + entityList[i];                                
                }
            }
            
            if (i%6==0)
                html[html.length] = "<tr>";
            else
                html[html.length] = "<tr class='alt'>";
                
            html[html.length] = "<td><a class='profile' href='/" + entityList[i+2] + "/" + entityList[i+1] + "/'>" + entityList[i+3] + "</td>";
            if (entityList[i] != "") {
                html[html.length] = "<td>" + entityList[i] + "</td>";
                html[html.length] = "<td class='price'><span id='" + cookieString + "_" + entityList[i] + "_price'>loading...</span></td>";
                html[html.length] = "<td class='change'><span id='" + cookieString + "_" + entityList[i] + "_change'>loading...</span>&nbsp;<span id='" + cookieString + "_" + entityList[i] + "_percent'></span></td></tr>";                
            } else {
                html[html.length] = "<td>--</td>";
                html[html.length] = "<td class='price'>--</td>";
                html[html.length] = "<td class='change'>--</td></tr>";                
            }
        }
        
        html[html.length] = "</tbody>";
        html[html.length] = "</table>";
        
    } else {
        html[html.length] = "<div class='no_recent'>There are no entities here.</div>"
    }
    
    return html;
}

function populateYears(tickers, ticker) {
    var html = "";
    var year_select = getElem("year_select");
    if (year_select != null) {
        html += "<select id='trans_year_select' class='trans_select'>\n";
        for (year in tickers[ticker]) {
            html +="<option value='" + tickers[ticker][year] + "'";
            if (year == tickers[ticker].length-1) {
                html += " selected ";
            }
            html += ">" + tickers[ticker][year] + "</option>";
        }
        html += "</select>\n";
        
        year_select.innerHTML = html;
    }
}


function filterFinancialComparison(id, field, quarter, year, period_end_date, period, value, company_name, company_uri, cbsa_code, cbsa_name, industry_id, industry_name, peds) {
    var histNode = getElem("hist_" + id);
    var histPEDNode = getElem("hist_" + id + "_ped");

    if (value != null) 
        value = value.replace(/\$/g,"").replace(/,/g,"").replace(/%/g,"");
    
    var cbsa_checked = "";
    if (cbsa_code == 0)
        cbsa_checked = "";
        
    var cbsa_checkbox = getElem("financial_geo_" + id);
    if (cbsa_checkbox != null)
        cbsa_checked = cbsa_checkbox.checked ? "checked" : "";
    
    var industry_checked = "checked";
    if (industry_id == 0)
        industry_checked = "";
        
    var industry_checkbox = getElem("financial_industry_" + id);
    if (industry_checkbox != null)
        industry_checked = industry_checkbox.checked ? "checked" : "";
        
    var loading = getElem(id + "_loading");
    if (loading != null) {
        loading.style.visibility = "visible";
    }
    
    var url = "/financial/histogram?tab_id=" + id + "&field=" + field + "&quarter=" + quarter + "&year=" + year + "&period=" + period + "&period_end_date=" + period_end_date + "&value=" + value + "&cbsa_code=" + cbsa_code + "&cbsa_name=" + cbsa_name + "&cbsa_checked=" + cbsa_checked + "&industry_id=" + industry_id + "&industry_name=" + industry_name + "&industry_checked=" + industry_checked + "&company_uri=" + company_uri + "&company_name=" + company_name + "&peds=" + peds;
    j.ajax({
        type: "GET",
        url: url,
        cache:false,
        success:
            function(data) {
                if (data) {
                    histNode.className = "compensation_comparison";
                    histNode.innerHTML = data;
                    histPEDNode.value = period_end_date;
                }
            }
    });
}



function showFinancialComparison(id, field, quarter, year, period_end_date, period, value, company_name, company_uri, cbsa_code, cbsa_name, industry_id, industry_name, peds, doPermaLink) {
    if (doPermaLink == null || doPermaLink) {
        var expandedFinancials = new Object();
        var financialStringArray = (window.location + "").split("#");
        var newKey = URLEncode(id + "|" + field + "|" + quarter + "|" + year + "|" + period_end_date + "|" + period + "|" + value + "|" + company_name + "|" + company_uri + "|" + cbsa_code + "|" + cbsa_name+ "|" + industry_id + "|" + industry_name + "|" + peds);
        var foundit = false;
        if (financialStringArray.length > 1 && financialStringArray[1] != "") {
            var financialRecords = financialStringArray[1].split("::");
            for (var i=0; i < financialRecords.length; i++) {
                if (financialRecords[i] != "") {
                    var financialVars = URLDecode(financialRecords[i]).split("|");
                    // e.g., key = revenue
                    expandedFinancials[financialVars[1]] = financialRecords[i];
                }
            }
            for (var k in expandedFinancials) {
                if (k == field && expandedFinancials[k] == newKey) {
                    foundit = true;
                    expandedFinancials[k] = "";
                }
            }
        }
        
        if (!foundit) {
            expandedFinancials[field] = newKey;
        }
    
        var financialVars = "";
        var i = 0;
        for (var k in expandedFinancials) {
            if (i > 0)
                financialVars += "::";
                
            if (expandedFinancials[k] != "") {
                financialVars += expandedFinancials[k];
            }
            i += 1;
        }
        
        window.location = "#" + financialVars;
    }
    
    var period_end_dates = peds.split(",");
    var histNode = getElem(id);
    var histShowingNode = getElem(id + "_showing");
    var histPEDNode = getElem("hist_" + id + "_ped");
    var tab = getElem(id + "_" + period_end_date);
    
    var doAjax = false;
    
    if (histPEDNode != null && histPEDNode.value != period_end_date) {
        doAjax = true;
    }
    
    for (var i=0; i < period_end_dates.length; i++) {
        var t = getElem(id + "_" + period_end_dates[i]);
        if (t != null && period_end_dates[i] != period_end_date) {
            t.className = "compensation_comparison_tab_notselected";
        }
    }
    // chart tab
    var t = getElem(id + "_chart");
    if (t != null && period_end_date != "chart") {
        t.className = "compensation_comparison_tab_notselected"; 
    }
    
    if (histPEDNode != null && histPEDNode.value == period_end_date) {
        j('#hist_' + id).toggle();
        if (tab != null) {
            if (tab.className == "compensation_comparison_tab_selected")
                tab.className = "compensation_comparison_tab_notselected";
            else
                tab.className = "compensation_comparison_tab_selected";
        }
    }
    else {
        var content = getElem("hist_" + id);
        if (content != null) {
            j(content).show();
            content.className = "compensation_comparison";
        }
    
        if (tab != null) {
            tab.className = "compensation_comparison_tab_selected";
        }
    }

    if (doAjax) {
        if (value == "chart") {
            var chart = getElem("chart_" + id);
            var content = getElem("hist_" + id);
            if (chart != null && content != null) {
                j(content).html(j(chart).html());
                content.className = "compensation_comparison";
            }
            var histPEDNode = getElem("hist_" + id + "_ped");
            if (histPEDNode != null) {
                histPEDNode.value = "chart";
            }
            var loading = getElem(id + "_loading");
            if (loading != null) {
                loading.style.visibility = "hidden";
            }
    
        } else {
            filterFinancialComparison(id, field, quarter, year, period_end_date, period, value, company_name, company_uri, cbsa_code, cbsa_name, industry_id, industry_name, peds);            
        }
    } else {
        var histPEDNode = getElem("hist_" + id + "_ped");
        if (histPEDNode != null) {
            histPEDNode.value = "";
        }
    }

}

function expandFinancials() {
    var financialStringArray = (window.location + "").split("#");
    if (financialStringArray.length > 1 && financialStringArray[1] != "") {
        var financialRecords= financialStringArray[1].split("::");
        for (var i=0; i < financialRecords.length; i++) {
            if (financialRecords[i] != "") {
                var financialVars = URLDecode(financialRecords[i]).split("|");
                showFinancialComparison(financialVars[0], financialVars[1], financialVars[2], financialVars[3], financialVars[4], financialVars[5], financialVars[6], financialVars[7], financialVars[8], financialVars[9], financialVars[10], financialVars[11], financialVars[12], financialVars[13], false);                            
            }
        }
    }
}


function filterCompensationComparison(id, company_uri, field, year, pos_id, pos_name, value, person_name, person_uri, cbsa_code, cbsa_name, industry_id, industry_name) {
    var histNode = getElem(id);
    var histFieldNode = getElem(id + "_field");

    if (value != null) 
        value = value.replace(/\$/g,"").replace(/,/g,"");
    
    var pos_checked = "checked";
    if (pos_id == 0)
        pos_checked = "";
        
    var position_checkbox = getElem("comp_position_" + id);
    if (position_checkbox != null)
        pos_checked = position_checkbox.checked ? "checked" : "";
    
    var cbsa_checked = "";
    if (cbsa_code == 0)
        cbsa_checked = "";
        
    var cbsa_checkbox = getElem("comp_geo_" + id);
    if (cbsa_checkbox != null)
        cbsa_checked = cbsa_checkbox.checked ? "checked" : "";
    
    var industry_checked = "checked";
    if (industry_id == 0)
        industry_checked = "";
        
    var industry_checkbox = getElem("comp_industry_" + id);
    if (industry_checkbox != null)
        industry_checked = industry_checkbox.checked ? "checked" : "";
        
    var loading = getElem(id + "_loading");
    if (loading != null) {
        loading.style.visibility = "visible";
    }
    
    var url = "/compensation/histogram?pos_checked=" + pos_checked + "&pos_id=" + pos_id + "&pos_name=" + pos_name + "&tab_id=" + id + "&person_name=" + person_name + "&person_uri=" + person_uri + "&field=" + field + "&year=" + year + "&value=" + value + "&cbsa_code=" + cbsa_code + "&cbsa_name=" + cbsa_name + "&cbsa_checked=" + cbsa_checked + "&industry_id=" + industry_id + "&industry_name=" + industry_name + "&industry_checked=" + industry_checked + "&company_uri=" + company_uri;
    j.ajax({
        type: "GET",
        url: url,
        cache:false,
        success:
            function(data) {
                if (data) {
                    histNode.className = "compensation_comparison";
                    histNode.innerHTML = data;
                    histFieldNode.value = field;
                }
            }
    });
}


function showCompensationComparison(id, company_uri, field, year, pos_id, pos_name, value, person_name, person_uri, cbsa_code, cbsa_name, industry_id, industry_name, doPermaLink) {
    if (doPermaLink == null || doPermaLink) {
        var expandedComps = new Object();
        var compStringArray = (window.location + "").split("#");
        var newKey = URLEncode(id + "|" + company_uri + "|" + field + "|" + year + "|" + pos_id + "|" + pos_name + "|" + value + "|" + person_name + "|" + person_uri + "|" + cbsa_code + "|" + cbsa_name+ "|" + industry_id + "|" + industry_name);
        var foundit = false;
        if (compStringArray.length > 1 && compStringArray[1] != "") {
            var compRecords = compStringArray[1].split("::");
            for (var i=0; i < compRecords.length; i++) {
                if (compRecords[i] != "") {
                    var compVars = URLDecode(compRecords[i]).split("|");
                    // e.g., key = microsoft_bill_gates_2008
                    expandedComps[compVars[1] + "_" + compVars[8] + "_" + compVars[3]] = compRecords[i];
                }
            }
            for (var k in expandedComps) {
                if (k == company_uri + "_" + person_uri + "_" + year && expandedComps[k] == newKey) {
                    foundit = true;
                    expandedComps[k] = "";
                }
            }
        }
        
        if (!foundit) {
            expandedComps[company_uri + "_" + person_uri + "_" + year] = newKey;
        }
    
        var compVars = "";
        var i = 0;
        for (var k in expandedComps) {
            if (i > 0)
                compVars += "::";
                
            if (expandedComps[k] != "") {
                compVars += expandedComps[k];
            }
            i += 1;
        }
        
        window.location = "#" + compVars;
    }
    
    var fields = ['salary', 'bonus', 'options', 'stock', 'pension_change', 'non_equity_incentive', 'other_compensation', 'total'];
    var histNode = getElem(id);
    var histShowingNode = getElem(id + "_showing");
    var histFieldNode = getElem(id + "_field");
    var tab = getElem(id + "_" + field);
    
    var doAjax = false;
    
    if (histFieldNode != null && histFieldNode.value != field) {
        doAjax = true;
    }
    
    if (false) {
        doAjax = true;
        histNode.className = "compensation_comparison compensation_comparison_loading";
        histNode.innerHTML = "loading...";       
    }
    
    for (var i=0; i < fields.length; i++) {
        var t = getElem(id + "_" + fields[i]);
        if (t != null && fields[i] != field) {
            t.className = "compensation_comparison_tab_notselected";
        }
    }
    if (histFieldNode != null && histFieldNode.value == field) {
        j('#' + id).slideToggle(250);
        if (tab != null) {
            if (tab.className == "compensation_comparison_tab_selected")
                tab.className = "compensation_comparison_tab_notselected";
            else
                tab.className = "compensation_comparison_tab_selected";
        }
    }
    else {
        j('#' + id).slideDown(250);
        if (tab != null) {
            tab.className = "compensation_comparison_tab_selected";
        }
    }

    if (doAjax) {
        filterCompensationComparison(id, company_uri, field, year, pos_id, pos_name, value, person_name, person_uri, cbsa_code, cbsa_name, industry_id, industry_name);
    } 

}


function expandCompensation() {
    var compStringArray = (window.location + "").split("#");
    if (compStringArray.length > 1 && compStringArray[1] != "") {
        var compRecords= compStringArray[1].split("::");
        for (var i=0; i < compRecords.length; i++) {
            if (compRecords[i] != "") {
                var compVars = URLDecode(compRecords[i]).split("|");
                showCompensationComparison(compVars[0], compVars[1], compVars[2], compVars[3], compVars[4], compVars[5], compVars[6], compVars[7], compVars[8], compVars[9], compVars[10], compVars[11], compVars[12], false);                            
            }
        }
    }
}

function toggleHistRange(id) {
    var bar = getElem(id + "_bar");
    
    if (bar != null) {
        if (bar.className.indexOf("_hover") >= 0) {
            bar.className = bar.className.split("_hover")[0];
            j('#' + id + "_range").fadeOut(100);
        }
        else {
            bar.className += "_hover";
            j('#' + id + "_range").fadeIn(100);
        }
    }
}

// returns milliseconds
function myRand(min, max) {
    var r = Math.floor(Math.random()*(max-min))
    return 1000 * (min + r)
}

function setActive(a) {
    global_activity = a;
}

function startInactivityTimer(e) {
    clearTimeout(asyncTimers["activity"]);
    asyncTimers["activity"] = setTimeout("setActive(false);", inactivityMS);
}

function stopInactivityTimer(e) {
    clearTimeout(asyncTimers["activity"]);
    setActive(true);
    updateMouseCoordinates(e);
}

function updateMouseCoordinates(e) {
	var posx = 0;
	var posy = 0;
	if (!e)
        e = window.event;
	
    if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft	+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	}
	
    global_mouse_x = posx;
    global_mouse_y = posy;
    
    // see if mouse has moved
    setTimeout(function() {checkMouseActivity(posx, posy);}, inactivityMS);
}

function checkMouseActivity(x, y) {
    if (x == global_mouse_x && y == global_mouse_y) {
        setActive(false);
    }
}

function jumpToExternalLink(feed_id, url) {
    window.open(url, feed_id);
}

function stopProp(e) {
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}


function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name+ "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + exdate.toGMTString()) + ";path=/";
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1) { 
            c_start=c_start + c_name.length+1; 
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1)
                c_end=document.cookie.length;
            
            return unescape(document.cookie.substring(c_start,c_end));
        } 
    }
    return "";
}

function deleteCookie(c_name) {
    var c_date = new Date ( );  // current date & time
    c_date.setTime (c_date.getTime() - 1);
    document.cookie = c_name += "=; expires=" + c_date.toGMTString();
}

function clearRecentEntitiesCookies() {
    deleteCookie("recentEntities");
    loadEntities("recentEntities");    
}

function clearRecentEntities(title_style) {
    //deleteCookie("recentEntities");
    //loadEntities("recentEntities");
    
    var loading = getElem("deleting_recent_entities");
    if (loading != null) {
        j(loading).show();
    }
    var url = "/tracker/clear_recent_entities";
    if (title_style == null) {
        title_style = "normal";
    }
    var params = {title_style:title_style}
    j.ajax({
        type: "POST",
        url: url,
        data:params,
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    var recent = getElem("recent_entities");
                    if (recent != null) {
                        j(recent).html(data);
                    }
                } else {
                    alert("Oops. Couldn't clear recent activity.");
                }
                if (loading != null) {
                    j(loading).hide();
                }
            }
    })
}


function showCompanySearchForJob(job_index) {
    var structured_name = getElem("structured_company_name_" + job_index);
    if (structured_name != null) {
        j(structured_name).hide();
        
        var input = getElem("company_search_" + job_index);
        if (input != null) {
            j(input).show();
        }

        var hidden_input = getElem("company_id_" + job_index);
        if (hidden_input != null) {
            hidden_input.value = "";
        }

        hidden_input = getElem("company_uri_" + job_index);
        if (hidden_input != null) {
            hidden_input.value = "";
        }
    }
    
}

function selectCompanyForJob(entity_id, entity_type, entity_uri, entity_name, job_index) {
    var structured_name = getElem("structured_company_name_" + job_index);
    if (structured_name != null) {
        j(structured_name).show();
        j(structured_name).html("<a class='profile' target='_new' href='/" + entity_type + "/" + entity_uri + "'>" + entity_name + "</a>&nbsp;&nbsp;<a class='edit' onclick='javascript:showCompanySearchForJob(" + job_index + ");' href='javascript:void(0);'>[edit]</a>");
        
        var search_input = getElem("company_search_" + job_index);
        if (search_input != null) {
            j(search_input).hide();
        }
        
        var hidden_input = getElem("company_id_" + job_index);
        if (hidden_input != null) {
            hidden_input.value = entity_id;
        }

        hidden_input = getElem("company_uri_" + job_index);
        if (hidden_input != null) {
            hidden_input.value = entity_uri;
        }
        closeProfileWatchlistSearch(job_index, 'company');
    }
}


function selectCustomCompanyForJob(job_index) {
    var entity_name = "";
    var add_company_text = getElem("add_company_text_" + job_index);
    if (add_company_text != null) {
        entity_name = add_company_text.value;
    }
    
    var structured_name = getElem("structured_company_name_" + job_index);
    if (structured_name != null) {
        j(structured_name).show();
        j(structured_name).html("<b>" + entity_name + "</b>&nbsp;&nbsp;<a class='edit' onclick='javascript:showCompanySearchForJob(" + job_index + ");' href='javascript:void(0);'>[edit]</a>");
        
        var search_input = getElem("company_search_" + job_index);
        if (search_input != null) {
            j(search_input).hide();
        }
        
        closeProfileWatchlistSearch(job_index, 'company');
    }
}

function toggleAddToWatchlistDropdown(entity_type, entity_uri) {
    var dropdown = getElem("add_profile_link_" + entity_type + "_" + entity_uri + "_dropdown");
    if (dropdown != null) {
        j(dropdown).toggle();
    }
}

function dontRecommendAnymore(entity_uri, entity_type, entity_id) {
    var ignore_link = getElem("ignore_link_" + entity_type + "_" + entity_uri + "_-1");
    if (ignore_link != null) {
        ignore_link.onclick = doNothing;
    }
    var recommended_row = getElem("row_" + entity_type + "_" + entity_uri + "_-1");
    if (recommended_row != null) {
        j(recommended_row).hide();
        totalIgnoredOrTrackedEntitiesCount++;
        if (totalRecommendedEntitiesCount <= totalIgnoredOrTrackedEntitiesCount) {
            var recommended_entities_section = getElem("recommended_entities_section");
            if (recommended_entities_section != null) {
                j(recommended_entities_section).hide();
            }
        }
        
        if (recommendedEntitiesBackfill != null) {
            if (recommendedEntitiesBackfill.length > recommendedEntitiesBackfillIndex) {
                var backfill_row = getElem(recommendedEntitiesBackfill[recommendedEntitiesBackfillIndex]);
                if (backfill_row != null) {
                    setTimeout(function() {
                        j(backfill_row).fadeIn();
                    }, 300);
                    recommendedEntitiesBackfillIndex++;
                }
            }
        }
    }

    var url = "/tracker/ignore_recommended_entity";
    j.ajax({
        type: "POST",
        url: url,
        data:"entity_id=" + entity_id + "&entity_type=" + entity_type,
        cache:false,
        success:
            function(data) {
                if (data != "0") {
                }
            }
    });
}

function toggleRecommendedWatchlistMenu(entity_id, entity_type) {
    
    var menu = getElem("recommended_watchlist_menu_" + entity_id + "_" + entity_type);
    if (menu != null) {
        if (menu.style.display == "none") {
            closeAllOpenMenus();            
        }
        j(menu).toggle();
    }
    
    if (menu.style.display != "none") {
        currentlyOpenMenus[currentlyOpenMenus.length] = menu;
    }
}

function trackProfile(entity_id, entity_type, entity_uri, entity_name, watchlist_id, backfillRecommended) {
    
    // recommended
    var fromRecommended = false;
    var link = getElem("track_recommended_link_" + entity_type + "_" + entity_uri + "_-1");
    if (link != null) {
        j(link).hide();
    }
    var check = getElem("track_recommended_check_" + entity_type + "_" + entity_uri + "_-1");
    if (check != null) {
        j(check).show();
    }

    var name = getElem("recommended_name_" + entity_type + "_" + entity_uri);
    if (name != null) {
        j(name).hide();
    }
    
    var tracked = getElem("recommended_nametracked_" + entity_type + "_" + entity_uri);
    if (tracked != null) {
        j(tracked).show();
    }

    if (backfillRecommended) {
        var recommended_row = getElem("row_" + entity_type + "_" + entity_uri + "_-1");
        if (recommended_row != null) {
            j(recommended_row).fadeOut(500);
            fromRecommended = true;
            totalIgnoredOrTrackedEntitiesCount++;
            if (totalRecommendedEntitiesCount <= totalIgnoredOrTrackedEntitiesCount) {
                var recommended_entities_section = getElem("recommended_entities_section");
                if (recommended_entities_section != null) {
                    j(recommended_entities_section).hide();
                }
            }
        }
        
        setTimeout(function() {
            if (recommendedEntitiesBackfill != null) {
                if (recommendedEntitiesBackfill.length > recommendedEntitiesBackfillIndex) {
                    var backfill_row = getElem(recommendedEntitiesBackfill[recommendedEntitiesBackfillIndex]);
                    if (backfill_row != null) {
                        setTimeout(function() {
                            j(backfill_row).fadeIn();
                        }, 300);
                        recommendedEntitiesBackfillIndex++;
                    }
                } else if (recommendedEntitiesBackfill.length <= recommendedEntitiesBackfillIndex) {
                    // hide recommended section
                    var recommended_entities_section = getElem("recommended_entites_section");
                    if (recommended_entities_section != null) {
                        j(recommended_entities_section).hide();
                    }
                }
            }
        }, 500);
    }

    // when adding from a profile page
    var add_to_watchlist_link = getElem("dropdown_item_selected_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
    if (add_to_watchlist_link != null) {
        j(add_to_watchlist_link).hide();
    }
    
    var remove_from_watchlist_link = getElem("dropdown_item_notselected_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
    if (remove_from_watchlist_link != null) {
        j(remove_from_watchlist_link).hide();
    }
    
    var loading_watchlist_link = getElem("dropdown_item_loading_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
    if (loading_watchlist_link != null) {
        j(loading_watchlist_link).show();
        var loading_watchlist_text = getElem("dropdown_item_loadingtext_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
        if (loading_watchlist_text != null) {
            j(loading_watchlist_text).html("adding " + entity_type);
        }
    }
    
    // when adding from tracker page
    var add_link = getElem("add_search_link_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
    if (add_link != null) {
        add_link.style.display = "none";
        var loading_link = getElem("add_link_loading_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
        if (loading_link != null) {
            loading_link.style.display = "block";
        }
    }
    var url = "/tracker/add_entity_to_watchlist";
    j.ajax({
        type: "POST",
        url: url,
        data:"entity_id=" + entity_id + "&entity_type=" + entity_type + "&watchlist_id=" + watchlist_id,
        cache:false,
        success:
            function(data) {
                if (data != "0") {
                    var tracker_section = getElem("my_watchlist_section_" + watchlist_id);
                    if (tracker_section != null) {
                        j(tracker_section).html(data);
                    }

                    var tracker_nav_link = getElem("tracker_nav_link");
                    if (tracker_nav_link != null) {
                        tracker_nav_link.className = "tracker_nav_link_selected";
                    }
                    
                    // when adding from a profile page
                    var add_to_watchlist_link = getElem("dropdown_item_selected_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
                    if (add_to_watchlist_link != null) {
                        j(add_to_watchlist_link).show();
                    }
                    
                    var remove_from_watchlist_link = getElem("dropdown_item_notselected_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
                    if (remove_from_watchlist_link != null) {
                        j(remove_from_watchlist_link).hide();
                    }
                    
                    var loading_watchlist_link = getElem("dropdown_item_loading_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
                    if (loading_watchlist_link != null) {
                        j(loading_watchlist_link).hide();
                    }

                    setTimeout(function() {
                        var highlight = getElem("row_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
                        if (highlight != null) {
                            highlight.className = "linkable";
                        }
                        var highlight = getElem("row_" + entity_type + "_" + entity_uri + "_alt" + "_" + watchlist_id);
                        if (highlight != null) {
                            highlight.className = "alt_OLD";
                        }
                    }, 3000);
                    
                    if (feed_entity_id == -1) {
                        var n = getElem("new_recent_feed_alert");
                        if (n != null)
                            j(n).hide();
                            
                        n = getElem("loading_recent_feed_alert");
                        if (n != null)
                            j(n).hide();

                        var alert = getElem("tracker_changed_alert");
                        if (alert != null) {
                        //    j(alert).show();                        
                        }
                        
                        var tracker_filter_id = getElem("tracker_filter_id");
                        var tracker_filter_id_value = "";
                        if (tracker_filter_id != null) {
                            tracker_filter_id_value = tracker_filter_id.value;
                        }
                            
                        var tracker_filter_type = getElem("tracker_filter_type");
                        var tracker_filter_type_value = "";
                        if (tracker_filter_type != null) {
                            tracker_filter_type_value = tracker_filter_type.value;
                        }
                        
                        var earlier_tracked_items = getElem("earlier_tracked_items");
                        if (tracker_section != null && earlier_tracked_items != null && tracker_filter_type_value == "" || tracker_filter_type_value == "watchlist") {
                            filterTrackedItems();
                        }

                        var tracked_items_msg = getElem("tracked_items_msg");
                        if (tracked_items_msg != null) {
                            j(tracked_items_msg).hide();
                        }
                    }

                    if (!fromRecommended) {
                        if (entity_type == "company")
                            toggleAddCompany(watchlist_id);
                        else if (entity_type == "person")
                            toggleAddPerson(watchlist_id);                        
                    }
                        
                } else {
                    var add_to_watchlist_link = getElem("add_profile_link_" + entity_type + "_" + entity_uri);
                    if (add_to_watchlist_link != null) {
                        j(add_to_watchlist_link).html("Tracker full! <a href='javascript:void(0);' class='emkcart' id='title:watchlist:add' onclick=\"javascript:trackProfile('" + entity_id + "','" + entity_type + "','" + entity_uri.replace(/\'/g,"\\\'") + "','" + entity_name.replace(/\'/g, "").replace(/\"/g,"") + "');\">[Try to track again]</a>");
                    }
                    myAlert("You have reached the maximum number of items in your tracker. Please delete one and try again.")
                    closeOverride = true;
                    closeProfileWatchlistSearch(watchlist_id, entity_type);
                }
            }
    });       
}

function myAlert(s) {
    alert(s);
}

function unTrackProfile(entity_id, entity_type, entity_uri, entity_name, watchlist_id) {
    // when adding from a profile page
    var add_to_watchlist_link = getElem("dropdown_item_selected_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
    if (add_to_watchlist_link != null) {
        j(add_to_watchlist_link).hide();
    }
    
    var remove_from_watchlist_link = getElem("dropdown_item_notselected_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
    if (remove_from_watchlist_link != null) {
        j(remove_from_watchlist_link).hide();
    }
    
    var loading_watchlist_link = getElem("dropdown_item_loading_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
    if (loading_watchlist_link != null) {
        j(loading_watchlist_link).show();
        var loading_watchlist_text = getElem("dropdown_item_loadingtext_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
        if (loading_watchlist_text != null) {
            j(loading_watchlist_text).html("removing " + entity_type);
        }
    }
    
    /*
    var remove_link_loading = getElem("remove_tracker_link_loading_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
    if (remove_link_loading != null) {        
        remove_link_loading.src = remove_link_loading.src.replace(/icon_trash.gif/g,"loading-small.gif");
    }
    */
    
    var row = getElem("row_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
    if (row != null) {
        j(row).fadeOut();
    }

    var url = "/tracker/remove_entity_from_watchlist";
    j.ajax({
        type: "POST",
        url: url,
        data:"entity_id=" + entity_id + "&entity_type=" + entity_type + "&watchlist_id=" + watchlist_id,
        cache:false,
        success:
            function(data) {
                if (data != "0") {

                    var entity_watchlist = getElem("my_watchlist_section_" + watchlist_id);
                    if (entity_watchlist != null) {
                        //j(entity_watchlist).html(data);
                        adjustWatchlistHeight();
                    }
                    
                    // when adding from a profile page
                    var add_to_watchlist_link = getElem("dropdown_item_selected_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
                    if (add_to_watchlist_link != null) {
                        j(add_to_watchlist_link).hide();
                    }
                    
                    var remove_from_watchlist_link = getElem("dropdown_item_notselected_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
                    if (remove_from_watchlist_link != null) {
                        j(remove_from_watchlist_link).show();
                    }
                    
                    var loading_watchlist_link = getElem("dropdown_item_loading_" + entity_type + "_" + entity_uri + "_" + watchlist_id);
                    if (loading_watchlist_link != null) {
                        j(loading_watchlist_link).hide();
                    }

                    if (feed_entity_id == -1) {
                        j('#new_recent_feed_alert').hide();
                        j('#loading_recent_feed_alert').hide();    
                        
                        var alert = getElem("tracker_changed_alert");
                        if (alert != null) {
                        //    j(alert).show();
                        }
                        
                        var tracker_filter_id = getElem("tracker_filter_id");
                        var tracker_filter_id_value = "";
                        if (tracker_filter_id != null) {
                            tracker_filter_id_value = tracker_filter_id.value;
                        }
                            
                        var tracker_filter_type = getElem("tracker_filter_type");
                        var tracker_filter_type_value = "";
                        if (tracker_filter_type != null) {
                            tracker_filter_type_value = tracker_filter_type.value;
                        }
                        
                        if (tracker_filter_type_value == "") {
                            filterTrackedItems();
                        }
                        
                        var tracked_items_msg = getElem("tracked_items_msg");
                        if (tracked_items_msg != null) {
                            j(tracked_items_msg).hide();
                        }
                    }

                } else {
                    alert("Oops! Unable to un-track item.");
                }
            }
    });    
}


function toggleAddTickers() {
    var addTickers = getElem("add_ticker_input");
    if (addTickers != null) {
        j("#add_ticker_input").toggle();
        var addTickersInput = getElem("add_ticker_text");
        if (addTickersInput != null) {
            addTickersInput.focus();
        }
    }
}

function doSubmitTickerSearch(event) {
   // if return key is pressed
    if (event.keyCode == 13) {
        doTickerSearch();
    }
}

function doTickerSearch() {
    var tickerInput = getElem("add_ticker_text");
    var ticker = null;
    if (tickerInput != null) {
        ticker = trim(tickerInput.value.toUpperCase());
    }
    
    if (ticker != null) {
        var tickerButton = getElem("add_ticker_button");
        if (tickerButton != null) {
            tickerButton.value = "Searching...";
            tickerButton.disabled = true;
        }
        var url = "/search/ticker";
        j.ajax({
            type: "POST",
            url: url,
            data: "ts=" + ticker,
            cache:false,
            success:
                function(data) {
                    if (data != null && data != "0" && trim(data) != "") {
                        var ticker_watchlist = getElem("my_ticker_watchlist_section");
                        if (ticker_watchlist != null) {
                            ticker_watchlist.innerHTML = data;
                        }
                        var add_to_watchlist_link = getElem("add_to_watchlist_link_" + ticker);
                        if (add_to_watchlist_link != null) {
                            add_to_watchlist_link.innerHTML = "Now watching " + ticker + "!";
                        }
                        var message = getElem("ticker_search_message");
                        setTimeout(function() {
                            var highlight = getElem("highlightedTicker");
                            if (highlight != null) {
                                highlight.className = "";
                            }
                            var highlight = getElem("highlightedTickerAlt");
                            if (highlight != null) {
                                highlight.className = "alt";
                            }
                        }, 3000);
                        
                        var tickerInput = getElem("add_ticker_text");
                        if (tickerInput != null) {
                            tickerInput.focus();
                        }
                    } else {
                        var tickerButton = getElem("add_ticker_button");
                        if (tickerButton != null) {
                            tickerButton.value = "Add Ticker";
                            tickerButton.disabled = false;
                        }

                        var message = getElem("ticker_search_message");
                        if (message != null) {
                            message.className = "market_down";
                            message.innerHTML = ticker + " not found.";
                            setTimeout(function() {
                                var message = getElem("ticker_search_message");
                                if (message != null) {
                                    message.innerHTML = "";
                                }
                            }, 3000);
                        } else {
                            alert("Oops! Unable to add item to Ticker Watchlist.");
                        }
                    }
                }
        });    

    }
    
}

function doSubmitProfileSearch(watchlist_id, event, entity_type, mode) {
   // if return key is pressed
    if (event.keyCode == 13) {
        doProfileSearch(watchlist_id, entity_type, mode);
    } else if (event.keyCode == 27) {
        closeProfileWatchlistSearch(watchlist_id, entity_type);
    }
}


function maybeDoProfileSearch(watchlist_id, entity_type, mode) {
    var results_node = getElem(entity_type + "_search_results_" + watchlist_id);
    if (results_node != null && results_node.style.display == "none") {
        doProfileSearch(watchlist_id, entity_type, mode);
    }    
}


function doProfileSearch(watchlist_id, entity_type, mode) {
    if (mode == null) {
        mode = "watchlist";
    } 
    
    var profileInput = getElem("add_" + entity_type + "_text_" + watchlist_id);
    var profile = null;
    if (profileInput != null) {
        profile = trim(profileInput.value);
        if (profile == "") {
            return;
        }
    }
    
    if (profile != null) {
        var profileButton = getElem("add_" + entity_type + "_button_" + watchlist_id);
        if (profileButton != null) {
            profileButton.value = "Searching...";
            profileButton.disabled = true;
        }
        
        var fakeProfileInput = getElem("fake_add_" + entity_type + "_text_" + watchlist_id)
        if (profileInput != null && fakeProfileInput != null) {
            j(profileInput).hide();
            j(fakeProfileInput).show();
            j(fakeProfileInput).html(profile);
        }
        
        var profileButton2dot0 = getElem("t2dot0_watchlist_search_button_" + watchlist_id);
        if (profileButton2dot0 != null) {
            j(profileButton2dot0).hide();
        }
        var profileLoading2dot0 = getElem("t2dot0_watchlist_search_loading_" + watchlist_id);
        if (profileLoading2dot0 != null) {
            j(profileLoading2dot0).show();
        }
        var url = "/search/" + entity_type;
        j.ajax({
            type: "POST",
            url: url,
            data: "q=" + profile + "&watchlist_id=" + watchlist_id + "&mode=" + mode,
            cache:false,
            success:
                function(data) {
                    if (data != null && data != "0" && trim(data) != "") {
                        var results_node = getElem(entity_type + "_search_results_" + watchlist_id);
                        if (results_node != null) {
                            j(results_node).html(data);
                            j(results_node).show();
                        }

                        if (profileButton != null) {
                            profileButton.value = "Search";
                            profileButton.disabled = false;
                        }
                        if (profileInput != null) {
                            profileInput.disabled = false;
                        }
                        
                        if (profileButton2dot0 != null) {
                            j(profileButton2dot0).show();
                        }

                        if (profileLoading2dot0 != null) {
                            j(profileLoading2dot0).hide();
                        }
                
                        if (profileInput != null && fakeProfileInput != null) {
                            j(profileInput).show();
                            j(fakeProfileInput).hide();
                        }
                     }
                }
        });    

    }
    
}

function closeNavPromotionBubbles() {
    var n = getElem('tracker_promotion_nav_bubble');
    if (n != null) {
        j(n).hide();
    }
    
    n = getElem('profile_promotion_nav_bubble');
    if (n != null) {
        j(n).hide();
    }

    n = getElem('connect_promotion_nav_bubble');
    if (n != null) {
        j(n).hide();
    }

    n = getElem('settings_promotion_nav_bubble');
    if (n != null) {
        j(n).hide();
    }

    n = getElem('message_promotion_nav_bubble');
    if (n != null) {
        j(n).hide();
    }
}

function closeAllPopups() {
    closeProfileWatchlistSearch("company");
    closeProfileWatchlistSearch("person");
    closeProfileWatchlistSearch(1, "user");
    closeTracker();
    hideVisibleOverlay();
    closeSearchDropdown();
    cancelShowPostInsight();
    closeObservationsDropdown('tracker');
    closeObservationsDropdown('nav');
    closeObservationsDropdown('overlay');
    closeAddToWatchlistDropdown();
    closeNavPromotionBubbles();
    
    // eventually get everything in here
    closeAllOpenMenus();
}

function closeAllOpenMenus() {
    for (m in currentlyOpenMenus) {
        if (currentlyOpenMenus[m] != null) {
            j(currentlyOpenMenus[m]).hide();
        }
    }
    
    currentlyOpenMenus = new Array();
}

function closeAddToWatchlistDropdown() {
    if (pp_entity_id > 0) {
        var dropdown = getElem("add_profile_link_" + pp_entity_type + "_" + pp_entity_uri + "_dropdown");
        if (dropdown != null) {
            j(dropdown).hide();
        }
    }
}

function toggleTrackerMessageDialog(unique) {
    var fake = getElem("fake_tracker_observation_dialog");
    if (fake != null) {
        j(fake).toggle();
    }

    var real = getElem("tracker_observation_dialog");
    if (real != null) {
        j(real).toggle();
    }
    
    var inputNode = getElem("observation_text_" + unique);
    if (inputNode != null && real != null && real.style.display != "none") {
        inputNode.focus();
    }
}

function closeProfileWatchlistSearch(watchlist_id, entity_type) {
    var results_node = getElem(entity_type + "_search_results_" + watchlist_id);
    if (results_node != null && (closeOverride || allowClose)) {
        closeOverride = false;
        j(results_node).hide();
    }
}

function delayCloseWatchlist() {
    allowClose = false;
    setTimeout(function() { allowClose = true;}, 500);
}

function showWatchlistOptions(watchlist_id) {
    var options = getElem("watchlist_options_link_" + watchlist_id);
    if (options != null) {
        //options.style.visibility = "visible";
    }
}

function hideWatchlistOptions(watchlist_id) {
    var options = getElem("watchlist_options_link_" + watchlist_id);
    if (options != null) {
        //options.style.visibility = "hidden";
    }
}

function toggleAddCompany(watchlist_id) {
    var sharing = getElem("edit_watchlist_sharing_" + watchlist_id);
    if (sharing != null) {
        j(sharing).hide();
    }
    
    var add = getElem("add_company_input_" + watchlist_id);
    if (add != null) {
        j(add).toggle();
        if (add.style.display != "none") {
            var txt = getElem("add_company_text_" + watchlist_id);
            if (txt != null) {
                txt.focus();
            }
        }
        adjustWatchlistHeight();
    }
    
    var options = getElem("watchlist_options_links_" + watchlist_id);
    if (options != null) {
        j(options).hide();
    }
    closeProfileWatchlistSearch(watchlist_id, "company");

   // tracker 2.0 stuff
    var large_add_button = getElem("large_add_button_" + watchlist_id);
    if (large_add_button != null) {
        j(large_add_button).toggle();
    }
        
     var t2dot0_add = getElem("t2dot0_watchlist_add_" + watchlist_id);
    if (t2dot0_add != null) {
        j(t2dot0_add).toggle();
        if (t2dot0_add.style.display != "none") {
            var txt = getElem("add_company_text_" + watchlist_id);
            if (txt != null) {
                txt.focus();
            }
        }
    }
}

function toggleAddPerson(watchlist_id) {
    var sharing = getElem("edit_watchlist_sharing_" + watchlist_id);
    if (sharing != null) {
        j(sharing).hide();
    }

    var add = getElem("add_person_input_" + watchlist_id);
    if (add != null) {
        j(add).toggle();
        if (add.style.display != "none") {
            var txt = getElem("add_person_text_" + watchlist_id);
            if (txt != null) {
                txt.focus();
            }
        }
        adjustWatchlistHeight();
    }
    var options = getElem("watchlist_options_links_" + watchlist_id);
    if (options != null) {
        j(options).hide();
    }
    closeProfileWatchlistSearch(watchlist_id, "person");
    
    // tracker 2.0 stuff
    var large_add_button = getElem("large_add_button_" + watchlist_id);
    if (large_add_button != null) {
        j(large_add_button).toggle();
    }
    
     var t2dot0_add = getElem("t2dot0_watchlist_add_" + watchlist_id);
    if (t2dot0_add != null) {
        j(t2dot0_add).toggle();
        if (t2dot0_add.style.display != "none") {
            var txt = getElem("add_person_text_" + watchlist_id);
            if (txt != null) {
                txt.focus();
            }
        }
    }
}

function toggleShowCompany(watchlist_id, collapsedImg, expandedImg) {
    var options = getElem("watchlist_options_" + watchlist_id);
    if (options != null) {
        j(options).toggle();
    }
    
    var add = getElem("add_entity_button_" + watchlist_id);
    if (add != null) {
        j(add).toggle();
    }
    
    var options_link = getElem("watchlist_options_link_" + watchlist_id);
    if (options_link != null) {
        j(options_link).toggle();
    }
    
    var table = getElem("company_watchlist_table_" + watchlist_id);
    if (table != null) {
        var img = getElem("company_watchlist_toggle_" + watchlist_id);
        if (img != null) {
            if (img.src == collapsedImg) {
                img.src = expandedImg;            
            } else {
                img.src = collapsedImg;
            }
        }
        j(table).toggle();
        j("#company_watchlist_show_tickers_" + watchlist_id).toggle();
        setCookie("companyTrackerSection_" + watchlist_id, table.style.display, 10000);
    }

    adjustWatchlistHeight();

}


function toggleShowPerson(watchlist_id, collapsedImg, expandedImg) {
    var options = getElem("watchlist_options_" + watchlist_id);
    if (options != null) {
        j(options).toggle();
    }
    
    var add = getElem("add_entity_button_" + watchlist_id);
    if (add != null) {
        j(add).toggle();
    }
    
    var options_link = getElem("watchlist_options_link_" + watchlist_id);
    if (options_link != null) {
        j(options_link).toggle();
    }
    
    var table = getElem("person_watchlist_table_" + watchlist_id);
    if (table != null) {
        var img = getElem("person_watchlist_toggle_" + watchlist_id);
        if (img != null) {
            if (img.src == collapsedImg) {
                img.src = expandedImg;            
            } else {
                img.src = collapsedImg;
            }
        }
        j(table).toggle();
        setCookie("personTrackerSection_" + watchlist_id, table.style.display, 10000);
    }

    adjustWatchlistHeight();

}


function toggleShowIndustry(watchlist_id, collapsedImg, expandedImg) {
    var options = getElem("watchlist_options_" + watchlist_id);
    if (options != null) {
        j(options).toggle();
    }
    
    var add = getElem("add_entity_button_" + watchlist_id);
    if (add != null) {
        j(add).toggle();
    }
    
    var options_link = getElem("watchlist_options_link_" + watchlist_id);
    if (options_link != null) {
        j(options_link).toggle();
    }
    
    var table = getElem("industry_watchlist_table_" + watchlist_id);
    if (table != null) {
        var img = getElem("industry_watchlist_toggle_" + watchlist_id);
        if (img != null) {
            if (img.src == collapsedImg) {
                img.src = expandedImg;            
            } else {
                img.src = collapsedImg;
            }
        }
        j(table).toggle();
        setCookie("industryTrackerSection_" + watchlist_id, table.style.display, 10000);
    }

    adjustWatchlistHeight();

}

function toggleTickerTracker(watchlist_id, set_c) {
    var hidOne = false;
    for (company in nonPublicCompanyURIs[watchlist_id]) {
        var row = getElem("row_company_" + nonPublicCompanyURIs[watchlist_id][company] + "_" + watchlist_id);
        if (row != null) {
            j(row).toggle();
            if (row.style.display == "none") {
                hidOne = true;
            }
        }
        var row = getElem("row_company_" + nonPublicCompanyURIs[watchlist_id][company] + "_alt_" + watchlist_id);
        if (row != null) {
            j(row).toggle();
            if (row.style.display == "none") {
                hidOne = true;
            }
        }
    }
    // if we hid one that means we're hiding companies
    if (hidOne) {
        var i = 0;
        for (company in publicCompanyURIs[watchlist_id]) {
            var row = getElem("row_company_" + publicCompanyURIs[watchlist_id][company] + "_" + watchlist_id);
            if (row != null) {
                if (i%2==0)
                    row.className = "";
                else
                    row.className = "alt";
                i++;                
            }
            var row = getElem("row_company_" + publicCompanyURIs[watchlist_id][company] + "_alt_" + watchlist_id);
            if (row != null) {
                if (i%2==0)
                    row.className = "";
                else
                    row.className = "alt";
                i++;                
            }
        }
    } else {
        var i = 0;
        for (company in companyURIs[watchlist_id]) {
            var row = getElem("row_company_" + companyURIs[watchlist_id][company] + "_" + watchlist_id);
            if (row != null) {
                if (i%2==0)
                    row.className = "";
                else
                    row.className = "alt";
                i++;                
            }
            var row = getElem("row_company_" + companyURIs[watchlist_id][company] + "_alt_" + watchlist_id);
            if (row != null) {
                if (i%2==0)
                    row.className = "";
                else
                    row.className = "alt";
                i++;                
            }
        }
        
    }
    
    if (set_c) {
        setCookie("tickersOnly_" + watchlist_id, getCookie("tickersOnly_" + watchlist_id)=="yes"?"no":"yes", 10000);
    }
    else {
        var cb = getElem("only_tickers_" + watchlist_id);
        if (cb != null) {
            cb.checked = true;
        }
    }
    
    adjustWatchlistHeight();

}

function possibleDoToggle() {
    var open_or_closed = getCookie("companyTrackerSection");
    if (open_or_closed != null && open_or_closed == "none") {
        toggleShowCompany(collapseImg, expandImg);
    }

    var tickersOnly = getCookie("tickersOnly");
    if (tickersOnly != null && tickersOnly == "yes") {
        toggleTickerTracker(false);
    }
}

function prepCompanyWatchlist(uri_list, ticker_uri_list, non_ticker_uri_list, watchlist_id) {
    var uris = uri_list.split(",");
    companyURIs[watchlist_id] = new Object();
    for (var i=0; i < uris.length; i++) {
        companyURIs[watchlist_id][uris[i]] = uris[i];
    }

    uris = ticker_uri_list.split(",");
    publicCompanyURIs[watchlist_id] = new Object();
    for (var i=0; i < uris.length; i++) {
        publicCompanyURIs[watchlist_id][uris[i]] = uris[i];
    }

    uris = non_ticker_uri_list.split(",");
    nonPublicCompanyURIs[watchlist_id] = new Object();
    for (var i=0; i < uris.length; i++) {
        nonPublicCompanyURIs[watchlist_id][uris[i]] = uris[i];
    }
}

function getNewTime(t) {
    newHTML = "";
    var parts = t.split(" ");
    if (parseInt(parts[0]) < 59 && (parts[1] == "min" || parts[1] == "minutes")) {
        var num = parseInt(parts[0])+1;
        newHTML += num + " " + parts[1];
        
        if (parts.length > 1 && parts[2] == "ago") {
            newHTML += " ago";
        }
    } else {
        newHTML = t;
    }
    
    return newHTML;
}

function toggleMoreTickers() {
    // for some reason jquery won't let me use toggle on more_tickers_content
    // but will let me use toggle on more_tickers_link. very strange.
    var more_tickers_content = getElem("more_tickers_content");
    if (more_tickers_content != null) {
        if (more_tickers_content.style.display != "none") {
            more_tickers_content.style.display = "none";
        } else {
            more_tickers_content.style.display = "block";
        }            
    }
    var more_tickers_link = getElem("more_tickers_link");
    if (more_tickers_link != null) {
        j(more_tickers_link).toggle();
    }
}

function getNewTimeFromEpoch(epoch, shorthand) {
    var d = new Date();
    var now_epoch = parseInt(d.getTime()/1000);
    var num_minutes_ago = parseInt((now_epoch-epoch)/60);

    var retVal = "";
    if (num_minutes_ago < 0) {
        retVal = "now";
    } else if (num_minutes_ago < 60) {
        retVal = num_minutes_ago + "&nbsp;min";
        if (!shorthand)
            retVal += "&nbsp;ago";
    } else if (num_minutes_ago/60 < 24) {
        if (parseInt(num_minutes_ago/60) == 1)
            retVal = parseInt(num_minutes_ago/60) + "&nbsp;hour";
        else
            retVal = parseInt(num_minutes_ago/60) + "&nbsp;hours";

        if (!shorthand)
            retVal += "&nbsp;ago";
    } else if (parseInt(num_minutes_ago/60/24) < 7) {
        if (parseInt(num_minutes_ago/60/24) == 1)
            retVal = parseInt(num_minutes_ago/60/24) + "&nbsp;day";
        else
            retVal = parseInt(num_minutes_ago/60/24) + "&nbsp;days";
            
        if (!shorthand)
            retVal += "&nbsp;ago";
    }
    
    return retVal;
}

function isNewTimeUrgent(epoch) {
    var d = new Date();
    var now_epoch = parseInt(d.getTime()/1000);
    var num_minutes_ago = parseInt((now_epoch-epoch)/60);
    
    if (num_minutes_ago <= 15) {
        return true;
    } 
    return false;
}

function updateMinutes() {
    j(".update_time").map(function (index) {
        // get new time from epoch
        var epoch = j(this).attr("id");
        if (epoch > 0) {
            var is_urgent = isNewTimeUrgent(epoch);
            j(this).html(getNewTimeFromEpoch(epoch, false));
            
            if (is_urgent)
                j(this).addClass("urgent");
            else
                j(this).removeClass("urgent");
        // var t = j(this).text();
        // j(this).html(getNewTime(t));
        }
    });    

    j(".update_time_shorthand").map(function (index) {
        // get new time from epoch
        var epoch = j(this).attr("id");
        if (epoch > 0) {
            var is_urgent = isNewTimeUrgent(epoch);
            j(this).html(getNewTimeFromEpoch(epoch, true));
            
            if (is_urgent)
                j(this).addClass("urgent");
            else
                j(this).removeClass("urgent");
        // var t = j(this).text();
        // j(this).html(getNewTime(t));
        }
    });    
}

function saveNewWatchlistOrder() {
    var ids = "";
    j(".tracker_section").map(function (index) {
        var id = j(this).attr("id");
        var items = id.split("_");
        ids += items[items.length-1] + ","
        var tracker = getElem("my_watchlist_section_" + items[items.length-1]);
        if (tracker != null) {
            var html = j(tracker).html();
            j(tracker).html("");
            j(tracker).html(html);
        }
        tracker = getElem("my_watchlist_section_" + items[items.length-1]);
        if (tracker != null) {
            var html = j(tracker).html();
            j(tracker).html("");
            j(tracker).html(html);
         }
        tracker = getElem("my_watchlist_section_" + items[items.length-1]);
        if (tracker != null) {
            var html = j(tracker).html();
            j(tracker).html("");
            j(tracker).html(html);
         }
    });     

    if (ids != "") {
        ids = ids.substring(0, ids.length-1);
    }
    
    var params = {watchlist_order:ids};
    var url = "/tracker/reorder_watchlist";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){          
            }
   });
}


function saveNewWatchlistOrderTracker2Dot0() {
    var ids = "";
    j(".filter_item").map(function (index) {
        var name = j(this).attr("name");
        if (name != null && name.indexOf("_") >= 0) {
            var items = name.split("_");
            ids += items[items.length-1] + ",";
        }
    });

    var summaryFilter = getElem("tracker_filter_1");
    if (summaryFilter != null) {
        var height = j(summaryFilter).height();
        j(summaryFilter).height(height+1);
        j(summaryFilter).height(height);
    }

    if (ids != "") {
        ids = ids.substring(0, ids.length-1);
    }
    
    // rearrange the thml
    var new_watchlist_html = "";
    var watchlists = new Object();
    var watchlist_ids = ids.split(",");
    for (id in watchlist_ids) {
        var watchlist_node = getElem("watchlist_section_container_" + watchlist_ids[id]);
        if (watchlist_node != null) {
            new_watchlist_html += "<div id='watchlist_section_container_" + watchlist_ids[id] + "'>" + j(watchlist_node).html() + "</div>";
        }
    }
    var all_watchlists_node = getElem("t2dot0_all_watchlists");
    if (all_watchlists_node != null) {
        j(all_watchlists_node).html(new_watchlist_html);
    }

    var params = {watchlist_order:ids};
    var url = "/tracker/reorder_watchlist";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
            }
   });
}

function toggleGrowthRates() {
    j(".financial_growth_rate").map(function (index) {
        j(this).toggle();
    });    
}

function toggleGrowthRateNumbers(field, i, highlight) {
    var value_current = getElem("cell_" + field + "_" + i);
    var value_past = getElem("cell_" + field + "_" + (i+1));

    if (highlight) {
        if (value_current != null) {
            value_current.className = "normal numerical highlighted";
        }
        if (value_past != null) {
            value_past.className = "normal numerical highlighted";
        }
    }
    else {
        if (value_current != null) {
            value_current.className = "normal numerical";
        }
        if (value_past != null) {
            value_past.className = "normal numerical";
        }
    }
}

function URLEncode(s)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = s;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}

function URLDecode(s)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = s;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   return plaintext;
}

function resizeMapPage() {
    var windowHeight = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
    var searchTable = getElem("scrollable_search_table");
    var search = getElem("scrollable_search");
    if (searchTable != null && search != null) {
        if (parseInt(windowHeight)-180 > 300) {
            searchTable.style.height = (parseInt(windowHeight)-210) + "px";
            search.style.height = (parseInt(windowHeight)-210) + "px";
        }
        else {
            searchTable.style.height = "300px";
            search.style.height = "300px";
        }
    }

}

function openMarkerOnMap(uri) {
    if (infos[uri].marker != null) {
        infos[uri].marker.openInfoWindowHtml(infos[uri].html);
        map.setCenter(infos[uri].point, 13);
    }
}

function toggleWatchlistRenameInput(watchlist_id) {
    var watchlist_name = getElem("watchlist_name_" + watchlist_id);
    if (watchlist_name != null) {
        j(watchlist_name).toggle();
    }

    var watchlist_count = getElem("watchlist_count_" + watchlist_id);
    if (watchlist_count != null) {
        j(watchlist_count).toggle();
    }

    var watchlist_rename = getElem("watchlist_rename_" + watchlist_id);
    if (watchlist_rename != null) {
        j(watchlist_rename).toggle();
        if (watchlist_rename.style.display != "none") {
            var rename_input = getElem("watchlist_rename_input_" + watchlist_id);
            if (rename_input != null) {
                rename_input.focus();
            }
        }
    }
}

function toggleWatchlistRenameLoading(watchlist_id) {
    var watchlist_rename_button_loading = getElem("watchlist_rename_button_loading_" + watchlist_id);
    if (watchlist_rename_button_loading != null) {
        j(watchlist_rename_button_loading).toggle();
    }
    
    var watchlist_rename_button = getElem("watchlist_rename_button_" + watchlist_id);
    if (watchlist_rename_button != null) {
        j(watchlist_rename_button).toggle();
    }

    var watchlist_cancel_button = getElem("watchlist_rename_cancel_button_" + watchlist_id);
    if (watchlist_cancel_button != null) {
        j(watchlist_cancel_button).toggle();
    }
}

function addTickerListToUpdate(ticker_list, key) {
    if (ticker_list == null) {
        return;
    }
    
    var t = null;
    var tickers = ticker_list.split(',');
    for (var i=0; i < tickers.length; i++) {
        t = tickers[i];
        if (tickerDict[t] == null) {
            tickerDict[t] = new Array();
        }        
        tickerDict[t][tickerDict[t].length] = key;
    }

}

function doUpdateAllTickers(msec) {
    if (!ajaxSemaphoreAvailable || !global_activity) {
        setTimeout("doUpdateAllTickers();", 2000);
        return;
    }
    
    if (msec == null) {
        msec = asyncRefreshRates['all_tickers'] + myRand(1,10);
    }
    
    _updateAllTickers(asyncTimers['all_tickers'], msec, "doUpdateAllTickers()");        
}

function sortOwnership(url) {
    var loading = getElem("ownership_loading_alert");
    if (loading != null) {
        loading.style.visibility = "visible";
    }
    setTimeout(function() {
        window.location = url;
    }, 0);
}

function _updateAllTickers(timer, timerRefreshRate, callback) {
    // clear the timer
    clearTimeout(timer);

    var ticker_list = "";
    for (t in tickerDict) {
        ticker_list += t + ",";
    }
    
    ajaxSemaphoreAvailable = false;
    var now = new Date();
    j.ajax({
        url: "/remote/tickers/?ts=" + ticker_list + "&forceienoncache=" + now.getSeconds(),
        cache: false,
        success:
        function(data){
            if (data) {
                parts = data.split("#");
                for (var i=0; i < parts.length; i++) {
                    quote = parts[i].split("|");
                    var symbol = quote[0];
                    var orig_symbol = quote[1];
                    var coded_symbol = quote[2];
                    var last_price = quote[3];
                    var last_change = quote[4];
                    var perc_change = quote[5];
                    var class_name = quote[6];
                    var day_of_week = quote[7];
                    var trade_date = quote[8];
                    var trade_time = quote[9];
                    var market_cap = quote[10];
                    var market_cap_change = quote[11];
                    var annual_low = quote[12];
                    var annual_high = quote[13];
                    var daily_low = quote[14];
                    var daily_high = quote[15];
                    var volume = quote[16];
                    var pe_ratio = quote[17];
                    var dividend = quote[18];
                    var div_yield = quote[19];
                    
                    // grab all the node id prefixes to update
                    var nodesList = tickerDict[orig_symbol];
                    if (nodesList != null) {
                        // change every node that requires it
                        for (var n=0; n < nodesList.length; n++) {
                            var key = nodesList[n];
                            var node = null;
                            
                            node = getElem(key + "_" + coded_symbol + "_price");
                            if (node != null) {
                                node.innerHTML = last_price;
                            }
                            
                            node = getElem(key + "_" + coded_symbol + "_change");
                            if (node != null) {
                                node.innerHTML = last_change;
                                node.className = class_name;
                            }
                            
                            node = getElem(key + "_" + coded_symbol + "_percent");
                            if (node != null) {
                                node.innerHTML = "(" + perc_change + "%)";
                                node.className = class_name;
                            }

                            node = getElem(key + "_" + coded_symbol + "_market_cap");
                            if (node != null) {
                                node.innerHTML = market_cap;
                            }

                            node = getElem(key + "_" + coded_symbol + "_market_cap_change");
                            if (node != null) {
                                node.innerHTML = market_cap_change;
                            }

                            node = getElem(key + "_" + coded_symbol + "_annual_low");
                            if (node != null) {
                                node.innerHTML = annual_low;
                            }

                            node = getElem(key + "_" + coded_symbol + "_annual_high");
                            if (node != null) {
                                node.innerHTML = annual_high;
                            }

                            node = getElem(key + "_" + coded_symbol + "_daily_low");
                            if (node != null) {
                                node.innerHTML = daily_low;
                            }

                            node = getElem(key + "_" + coded_symbol + "_daily_high");
                            if (node != null) {
                                node.innerHTML = daily_high;
                            }

                            node = getElem(key + "_" + coded_symbol + "_day_of_week");
                            if (node != null) {
                                node.innerHTML = day_of_week;
                            }

                            node = getElem(key + "_" + coded_symbol + "_trade_date");
                            if (node != null) {
                                node.innerHTML = trade_date;
                            }

                            node = getElem(key + "_" + coded_symbol + "_trade_time");
                            if (node != null) {
                                node.innerHTML = trade_time;
                            }

                            node = getElem(key + "_" + coded_symbol + "_volume");
                            if (node != null) {
                                node.innerHTML = volume;
                            }

                            node = getElem(key + "_" + coded_symbol + "_pe_ratio");
                            if (node != null) {
                                node.innerHTML = pe_ratio;
                            }

                            node = getElem(key + "_" + coded_symbol + "_dividend");
                            if (node != null) {
                                node.innerHTML = dividend;
                            }

                            node = getElem(key + "_" + coded_symbol + "_div_yield");
                            if (node != null) {
                                node.innerHTML = div_yield;
                            }
                        }
                    }
                    
                   
                }
            }
            ajaxSemaphoreAvailable = true;
            timer = setTimeout(callback, timerRefreshRate + myRand(1,10));
        }
   });    
}

function selectWatchlistRow(node_id) {
    if (selectedTrackerCenterPaneRow != null) {
        selectedTrackerCenterPaneRow.className = "";
    }
    
    var node = getElem(node_id);
    if (node != null) {
        node.className = "selected";
        selectedTrackerCenterPaneRow = node;
    }
}

function selectTrackedDataTab(label) {
    if (trackerDataLabelTabSelected == null) {
        trackerDataLabelTabSelected = "headlines";
    }
    
    if (label != trackerDataLabelTabSelected) {

        // select the appropriate tab on top
        var t2dot0_nav_label_tab = getElem("t2dot0_nav_" + label + "_tab");
        if (t2dot0_nav_label_tab != null) {
            j(t2dot0_nav_label_tab).addClass("nav_item_selected");
            j(t2dot0_nav_label_tab).removeClass("nav_item");
        }
        
        
        // unselect the previously selected tab
        t2dot0_nav_label_tab = getElem("t2dot0_nav_" + trackerDataLabelTabSelected + "_tab");
        if (t2dot0_nav_label_tab != null) {
            j(t2dot0_nav_label_tab).addClass("nav_item");
            j(t2dot0_nav_label_tab).removeClass("nav_item_selected");
        }        
    
        // select the appropriate tab on bottom
        var t2dot0_nav_label = getElem("t2dot0_nav_" + label);
        if (t2dot0_nav_label != null) {
            j(t2dot0_nav_label).addClass("nav_item_selected_notab");
            j(t2dot0_nav_label).removeClass("nav_item");
        }
        
        // unselect the previously selected tab
        if (trackerDataLabelTabSelected != null) {
            t2dot0_nav_label = getElem("t2dot0_nav_" + trackerDataLabelTabSelected);
            if (t2dot0_nav_label != null) {
                j(t2dot0_nav_label).addClass("nav_item");
                j(t2dot0_nav_label).removeClass("nav_item_selected_notab");
            }        
        }
        
        trackerDataLabelTabSelected = label;        
    }
    
}


function getTrackedData(entity_type, entity_uri, label) {
    selectTrackedDataTab(label);

    var tracked_data_loading = getElem("tracked_data_loading");
    if (tracked_data_loading != null) {
        j(tracked_data_loading).show();
    }
    var tracked_items_loading = getElem("tracked_items_loading");
    if (tracked_items_loading != null) {
        j(tracked_items_loading).show();
    }

    var params = {entity_uri:entity_uri, label:label};
    var url = "/" + entity_type + "/" + entity_uri + "/module/";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    var tracked_data_loading = getElem("tracked_data_loading");
                    if (tracked_data_loading != null) {
                        j(tracked_data_loading).hide();
                    }

                    var t2dot0_news_content = getElem("t2dot0_news_content");
                    if (t2dot0_news_content != null) {
                        j(t2dot0_news_content).hide();
                    }
                
                    var t2dot0_data_content = getElem("t2dot0_data_content");
                    if (t2dot0_data_content != null) {
                        j(t2dot0_data_content).show();
                    }
                    
                    var t2dot0_data_content_container = getElem("t2dot0_data_content_container");
                    if (t2dot0_data_content_container != null) {
                        j(t2dot0_data_content_container).html(data);
                    }                   
                }
            }
    });

}


function filterTrackedItems(filter_id, filter_type, filter_name, entity_uri_redirect) {
    // null out all the params
    var earliest_observation_date = getElem("earliest_observation_date");
    if (earliest_observation_date != null) {
        earliest_observation_date.value = "";
    }
    
    var earliest_observation_id = getElem("earliest_observation_id");
    if (earliest_observation_id != null) {
        earliest_observation_id.value = "-1";
    }
        
    var earliest_headline_date = getElem("earliest_headline_date");
    if (earliest_headline_date != null) {
        earliest_headline_date.value = "";
    }
        
    var earliest_headline_id = getElem("earliest_headline_id");
    var earliest_headline_id_value = "";
    if (earliest_headline_id != null) {
        earliest_headline_id.value = "-1";
    }
 
    if (filter_id > 0 && filter_type == "filter") {
        j(".filter_item.filter_item_selected").removeClass("filter_item_selected");
        j("#tracker_filter_" + filter_id).addClass("filter_item_selected");        
    }
    
    window.location = "#";
    
    if (filter_id == 1 && filter_type == "filter")
        getTrackedSummary(filter_id, filter_name);
    else
        getTrackedItems("replace", filter_id, filter_type, filter_name, entity_uri_redirect);
}



function getTrackedItems(replace, filter_id, filter_type, filter_name, entity_uri_redirect) {
    selectTrackedDataTab("headlines");

    var tracked_data_loading = getElem("tracked_data_loading");
    if (tracked_data_loading != null) {
        j(tracked_data_loading).show();
    }

    ajaxSemaphoreAvailable = false;
    
    // if not on the tracker page
    var earlier_tracked_items = getElem("earlier_tracked_items");
    if (earlier_tracked_items == null && entity_uri_redirect != null) {
        window.location = "/" + filter_type + "/" + entity_uri_redirect + "/news/";
        return false;
    }

    // either set or get the filter id
    var tracker_filter_id = getElem("tracker_filter_id");
    if (filter_id == null) {
        if (tracker_filter_id != null) {
            filter_id = tracker_filter_id.value;
        }
    } else {
        if (tracker_filter_id != null) {
            tracker_filter_id.value = filter_id;            
        }
    }
    
    // either set or get the filter id
    var tracker_filter_type = getElem("tracker_filter_type");
    if (filter_type == null) {
        if (tracker_filter_type != null) {
            filter_type = tracker_filter_type.value;
        }
    } else {
        if (tracker_filter_type != null) {
            tracker_filter_type.value = filter_type;            
        }
    }
        
    var title = getElem("tracked_items_title");
    if (false && title != null) {
        var new_title = getElem("tracker_filter_name_" + filter_id);
        if (new_title != null) {
            j(title).html("Loading \"" + new_title.value + "\"");
        }
    }
    
    if (replace == "append") {
        var loading = getElem("loading_earlier_image");
        if (loading != null) {
            loading.style.visibility = "visible";
        }
    } else if (replace == "replace") {
        var loading = getElem("tracker_filter_loading_" + filter_id);
        if (loading != null) {
            loading.style.visibility = "visible";
        }
        
        var edit_filter_link = getElem("edit_filter_" + filter_id);
        if (edit_filter_link != null) {
            edit_filter_link.style.visibility = "hidden";
        }

        // erase the new tracked items
        new_tracked_content = new NewTrackedContent();

        var tracked_items_loading = getElem("tracked_items_loading");
        if (tracked_items_loading != null) {
            j(tracked_items_loading).show();
        }
        
        var tracked_items_msg = getElem("tracked_items_msg");
        if (tracked_items_msg != null) {
            j(tracked_items_msg).hide();
        }

        var tracker_changed_alert = getElem("tracker_changed_alert");
        if (tracker_changed_alert != null) {
            j(tracker_changed_alert).hide();
        }
        
    }
    
    // observations specific stuff
    var earliest_observation_date = getElem("earliest_observation_date");
    var earliest_observation_date_value = "";
    if (earliest_observation_date != null) {
        earliest_observation_date_value = earliest_observation_date.value;
    }
    
    var earliest_observation_id = getElem("earliest_observation_id");
    var earliest_observation_id_value = "";
    if (earliest_observation_id != null) {
        earliest_observation_id_value = earliest_observation_id.value;
    }
        
    var earliest_headline_date = getElem("earliest_headline_date");
    var earliest_headline_date_value = "";
    if (earliest_headline_date != null) {
        earliest_headline_date_value = earliest_headline_date.value;
    }
        
    var earliest_headline_id = getElem("earliest_headline_id");
    var earliest_headline_id_value = "";
    if (earliest_headline_id != null) {
        earliest_headline_id_value = earliest_headline_id.value;
    }
        
    if (filter_type == null) {
        filter_type = "";    
    }
    
    var params = {earliest_observation_date:earliest_observation_date_value,
                earliest_observation_id:earliest_observation_id_value,
                earliest_headline_date:earliest_headline_date_value,
                earliest_headline_id:earliest_headline_id_value,
                filter_id:filter_id,
                filter_type:filter_type}
                
    var url = "/tracker/get_tracked_items";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    var t2dot0_news_content = getElem("t2dot0_news_content");
                    if (t2dot0_news_content != null) {
                        j(t2dot0_news_content).show();
                    }
                    var tracked_data_loading = getElem("tracked_data_loading");
                    if (tracked_data_loading != null) {
                        j(tracked_data_loading).hide();
                    }
                    var t2dot0_data_content = getElem("t2dot0_data_content");
                    if (t2dot0_data_content != null) {
                        j(t2dot0_data_content).hide();
                    }

                    var results = data.split("<!--divider-->")
                    
                    var theHtml = trim(results[0]);
                    var earliest_observation_date_string = trim(results[1]);
                    var earliest_observation_id_string = trim(results[2]);
                    var earliest_headline_date_string = trim(results[3]);
                    var earliest_headline_id_string = trim(results[4]);
                    var latest_observation_date_string = trim(results[5]);
                    var latest_observation_id_string = trim(results[6]);
                    var latest_headline_date_string = trim(results[7]);
                    var latest_headline_id_string = trim(results[8]);
                    var show_earlier_string = trim(results[9]);
                    var filter_insights_value = trim(results[10]);
                    var nav_data = trim(results[11]);
                    var links_data = trim(results[12]);
                    var entity_uri = trim(results[13]);
                    
                    var earlier_tracked_items = getElem("earlier_tracked_items");
                    if (earlier_tracked_items != null) {
                        if (replace == "append")
                            j(earlier_tracked_items).append(theHtml);
                        else if (replace == "prepend")
                            j(earlier_tracked_items).prepend(theHtml);
                        else {
                            j(earlier_tracked_items).html(theHtml);
                            var t2dot0_summary_content = getElem("t2dot0_summary_content");
                            if (t2dot0_summary_content != null) {
                                j(t2dot0_summary_content).html("");
                                j(t2dot0_summary_content).hide();
                            }
                        }
                    }

                    if (earliest_observation_date != null) {
                        earliest_observation_date.value = earliest_observation_date_string;
                    }
                    if (earliest_observation_id != null) {
                        earliest_observation_id.value = earliest_observation_id_string;
                    }
                    if (earliest_headline_date != null) {
                        earliest_headline_date.value = earliest_headline_date_string;
                    }
                    if (earliest_headline_id != null) {
                        earliest_headline_id.value = earliest_headline_id_string;
                    }
                    
                    // if we are replacing content, let's record the latest dates too
                    if (replace == "replace") {
                        // clear my new observations
                        var observation_list = getElem("observation_list");
                        if (observation_list != null) {
                            j(observation_list).html("");
                        }

                        var latest_observation_date = getElem("latest_observation_date");
                        if (latest_observation_date != null) {
                            latest_observation_date.value = latest_observation_date_string;
                        }
                        
                        var latest_observation_id = getElem("latest_observation_id");
                        if (latest_observation_id != null) {
                            latest_observation_id.value = latest_observation_id_string;
                        }
                        
                        var latest_headline_date = getElem("latest_headline_date");
                        if (latest_headline_date != null) {
                            latest_headline_date.value = latest_headline_date_string;
                        }
                        
                        var latest_headline_id = getElem("latest_headline_id");
                        if (latest_headline_id != null) {
                            latest_headline_id.value = latest_headline_id_string;
                        }
                    }

                    
                    if (show_earlier_string == "0") {
                        var load_earlier_tracked_items = getElem("load_earlier_tracked_items");
                        if (load_earlier_tracked_items != null) {
                            j(load_earlier_tracked_items).hide();
                        }
                    } else {
                        var load_earlier_tracked_items = getElem("load_earlier_tracked_items");
                        if (load_earlier_tracked_items != null) {
                            j(load_earlier_tracked_items).show();
                        }
                    }
                    
                    // do we show the message in the news feed after sending from nav?
                    if (filter_insights_value == "all" || filter_insights_value == "self") {
                        showSelfMessagesAfterSend = true;
                    } else {
                        showSelfMessagesAfterSend = false;                        
                    }
                    
                    if (filter_insights_value == "direct") {
                        showDirectMessagesAfterSend = true;
                    } else {
                        showDirectMessagesAfterSend = false;
                    }
                    
                    // maybe show nav data
                    if (nav_data != "-1" && links_data != "-1") {
                        var t2dot0_newsdata_nav = getElem("t2dot0_newsdata_nav");
                        if (t2dot0_newsdata_nav != null) {
                            j(t2dot0_newsdata_nav).show();
                            j(t2dot0_newsdata_nav).html(nav_data);
                        }
                        var t2dot0_newsdata_links = getElem("t2dot0_newsdata_links");
                        if (t2dot0_newsdata_links != null) {
                            j(t2dot0_newsdata_links).show();
                            j(t2dot0_newsdata_links).html(links_data);
                        }
                    } else {
                        var t2dot0_newsdata_nav = getElem("t2dot0_newsdata_nav");
                        if (t2dot0_newsdata_nav != null) {
                            j(t2dot0_newsdata_nav).hide();
                        }                        
                        var t2dot0_newsdata_links = getElem("t2dot0_newsdata_links");
                        if (t2dot0_newsdata_links != null) {
                            j(t2dot0_newsdata_links).hide();
                        }                        
                    }

                } else {
                    alert("Error loading tracked items. Please try again.");
                }

                if (loading != null) {
                    loading.style.visibility = "hidden";
                }
                    
                if (edit_filter_link != null) {
                    edit_filter_link.style.visibility = "visible";
                }

                if (title != null && filter_name != null) {
                    var title_text = "";
                    if (filter_type == "company" || filter_type == "person" || filter_type == "industry") {
                        title_text = "<a href='/" + filter_type + "/" + entity_uri + "/' class='profile'>" + filter_name + "</a>";
                    } else if (filter_type == "user") {
                        title_text = "Messages from <a href='/user/" + entity_uri_redirect + "/' class='profile'>" + filter_name + "</a>";
                        if (selectedTrackerFilter != null && selectedTrackerFilter.insights == "direct") {
                            title_text += " to you";
                        }
                    } else {
                        title_text = filter_name;
                    }
                    j(title).html(title_text);
                }

                var tracked_items_loading = getElem("tracked_items_loading");
                if (tracked_items_loading != null) {
                    j(tracked_items_loading).hide();
                }
                ajaxSemaphoreAvailable = true;

            }
        }
    );
}


function showNewTrackedItems() {
    if (new_tracked_content != null) {
        // hide new message
        var tracked_items_msg = getElem("tracked_items_msg");
        if (tracked_items_msg != null) {
            j(tracked_items_msg).hide();
        }

        // put new content
        var earlier_tracked_items = getElem("earlier_tracked_items");
        if (earlier_tracked_items != null) {
            var tracked_items_loading = getElem("tracked_items_loading");
            if (tracked_items_loading != null) {
                j(tracked_items_loading).show();
            }
            
            if (!trackedSemaphoreAvailable) {
                showTrackedNewTimesImmediately = true;
                return;
            }
            
            // clear my new observations
            var observation_list = getElem("observation_list");
            if (observation_list != null) {
                j(observation_list).html("");
            }

            var d = new Date();
            var node_id_string = "new_tracked_content_" + d.getTime();
            j(earlier_tracked_items).prepend("<div style='display:none;' id='" + node_id_string + "'>" + new_tracked_content.html + "</div>");

            
            var node_id = getElem(node_id_string);
            if (node_id != null) {
                j(node_id).fadeIn();
            }

            var tracked_items_loading = getElem("tracked_items_loading");
            if (tracked_items_loading != null) {
                j(tracked_items_loading).hide();
            }

            // update time stamps in case of stale ones
            updateMinutes();
        }
        
        // observations specific stuff
        var latest_observation_date = getElem("latest_observation_date");
        if (latest_observation_date != null) {
            latest_observation_date.value = new_tracked_content.latest_observation_date;
        }
        
        var latest_observation_id = getElem("latest_observation_id");
        if (latest_observation_id != null) {
            latest_observation_id.value = new_tracked_content.latest_observation_id;
        }
            
        var latest_headline_date = getElem("latest_headline_date");
        if (latest_headline_date != null) {
            latest_headline_date.value = new_tracked_content.latest_headline_date;
        }
            
        var latest_headline_id = getElem("latest_headline_id");
        if (latest_headline_id != null) {
            latest_headline_id.value = new_tracked_content.latest_headline_id;
        }
        
    }
}


function scheduleGetNewTrackedItems(msec) {
    if (msec == null)
        msec = asyncRefreshRates['tracked_items'] + myRand(1,10);
        
    clearTimeout(asyncTimers['tracked_items']);
    asyncTimers['tracked_items'] = setTimeout("getNewTrackedItems()", msec);
}


function getNewTrackedItems() {
    if (!ajaxSemaphoreAvailable || !feedsSemaphoreAvailable || !global_activity) {
        scheduleGetNewTrackedItems(2000);   
        return;
    }

    ajaxSemaphoreAvailable = false;
    trackedSemaphoreAvailable = false;
    
    // observations specific stuff
    var latest_observation_date = getElem("latest_observation_date");
    var latest_observation_date_value = "";
    if (latest_observation_date != null) {
        latest_observation_date_value = latest_observation_date.value;
    }
    
    var latest_observation_id = getElem("latest_observation_id");
    var latest_observation_id_value = "";
    if (latest_observation_id != null) {
        latest_observation_id_value = latest_observation_id.value;
    }
        
    var latest_headline_date = getElem("latest_headline_date");
    var latest_headline_date_value = "";
    if (latest_headline_date != null) {
        latest_headline_date_value = latest_headline_date.value;
    }
        
    var latest_headline_id = getElem("latest_headline_id");
    var latest_headline_id_value = "";
    if (latest_headline_id != null) {
        latest_headline_id_value = latest_headline_id.value;
    }
        
    var tracker_filter_id = getElem("tracker_filter_id");
    var tracker_filter_id_value = "";
    if (tracker_filter_id != null) {
        tracker_filter_id_value = tracker_filter_id.value;
    }
        
    var tracker_filter_type = getElem("tracker_filter_type");
    var tracker_filter_type_value = "";
    if (tracker_filter_type != null) {
        tracker_filter_type_value = tracker_filter_type.value;
    }
        
    var params = {latest_observation_date:latest_observation_date_value,
                latest_observation_id:latest_observation_id_value,
                latest_headline_date:latest_headline_date_value,
                latest_headline_id:latest_headline_id_value,
                filter_id:tracker_filter_id_value,
                filter_type:tracker_filter_type_value}
                
    var url = "/tracker/get_new_tracked_items";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    var results = data.split("<!--divider-->")
                    
                    new_tracked_content = new NewTrackedContent();
                    new_tracked_content.html = trim(results[0]);
                    
                    var latest_observation_date = trim(results[1]);
                    if (latest_observation_date != "")
                        new_tracked_content.latest_observation_date = latest_observation_date;

                    var latest_observation_id = trim(results[2]);
                    if (latest_observation_date != "")
                        new_tracked_content.latest_observation_id = latest_observation_date;
                        
                    var latest_headline_date = trim(results[3]);
                    if (latest_headline_date != "")
                        new_tracked_content.latest_headline_date = latest_headline_date;
                        
                    var latest_headline_id = trim(results[4]);
                    if (latest_headline_id != "")
                        new_tracked_content.latest_headline_id = latest_headline_id;
                    
                    var num_observations = trim(results[5]);
                    if (num_observations != "") 
                        new_tracked_content.num_observations = num_observations;
                    
                    var num_sent_observations = trim(results[6]);
                    if (num_sent_observations != "")
                        new_tracked_content.num_sent_observations = num_sent_observations;
                        
                    var num_received_observations = trim(results[7]);
                    if (num_received_observations != "")
                        new_tracked_content.num_received_observations = num_received_observations;
                        
                    var num_headlines = trim(results[8]);
                    if (num_headlines != "")
                        new_tracked_content.num_headlines = num_headlines;
                    
                    // show new message if there are insights or headlines
                    if (parseInt(num_received_observations) > 0 || parseInt(num_headlines) > 0) {
                        var num_tracked_items = getElem("num_tracked_items");
                        if (num_tracked_items != null) {
                            j(num_tracked_items).html(parseInt(num_received_observations) + parseInt(num_headlines));
                        }
                        
                        var tracked_items_loading = getElem("tracked_items_loading");
                        if (tracked_items_loading != null) {
                            j(tracked_items_loading).hide();
                        }
                        
                        var tracked_items_msg = getElem("tracked_items_msg");
                        if (tracked_items_msg != null) {
                            j(tracked_items_msg).show();
                        }

                        var alert = getElem("tracker_changed_alert");
                        if (alert != null)
                            j(alert).hide();                        
                    }
                } else {
                }

                ajaxSemaphoreAvailable = true;
                trackedSemaphoreAvailable = true;
                scheduleGetNewTrackedItems();
                
                if (showTrackedNewTimesImmediately) {
                    showTrackedNewTimesImmediately = false;
                    showNewTrackedItems();
                }
            }
        }
    );
}



function deleteObservation(observation_id) {
    var del = window.confirm("Are you sure you want to delete this message?");
    if (!del) {
        return;
    }
    
    var params = {observation_id:observation_id};
    var url = "/tracker/delete_observation";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    var observation = getElem("observation_" + observation_id);
                    if (observation != null) {
                        j(observation).fadeOut(500);
                    }
                } else {
                    alert("Error deleting observation. Please try again.");
                }
            }
   });    
}

function toggleNodeDisplay(nodeId) {
    var d = getElem(nodeId);
    if (d != null) {
        j(d).toggle();
    }
}

function toggleChangePhotoForm() {
    var changePhotoForm = getElem("changePhotoForm");
    if (changePhotoForm != null) {
        j(changePhotoForm).toggle();
    }
    
    var changePhotoLink = getElem("changePhotoLink");
    if (changePhotoLink != null) {
        j(changePhotoLink).toggle();
    }
}

function changeOwnershipTrendTab(key) {
    // change the tabs
    var tab_node = null;
    if (ownership_trend_tabs != null) {
        for (tab in ownership_trend_tabs) {
            tab_node = getElem("ownership_trend_nav_" + ownership_trend_tabs[tab]);
            if (tab_node != null) {
                tab_node.className = "intranav_dark ownership_trend_nav";
            }
        }

        tab_node = getElem("ownership_trend_nav_" + key);
        if (tab_node != null) {
            tab_node.className = "intranav_dark intranav_dark_selected ownership_trend_nav";
        }

    }

    // show the content
    var chart_node = null;
    if (ownership_trend_tabs != null) {
        for (tab in ownership_trend_tabs) {
            chart_node = getElem("ownership_trend_chart_" + ownership_trend_tabs[tab]);
            if (chart_node != null) {
                j(chart_node).hide();
            }
        }

        chart_node = getElem("ownership_trend_chart_" + key);
        if (chart_node != null) {
            j(chart_node).show();
        }

    }

}

// selects source type in the news feed well of tracker,
// sets the cookie
function selectNewsFeedFilterCB(source_type) {
    var is_unchecked = "";
    var cb = getElem(source_type + "_trackerfeed_cb");
    var label = getElem(source_type + "_trackerfeed_cb_label");
    var filter_watchlist_id = getElem("filter_watchlist_id");
    if (cb != null && label != null && filter_watchlist_id != null) {
        if (!cb.checked) {
            is_unchecked = "unchecked";
            label.style.fontWeight = "normal";
        } else {
            label.style.fontWeight = "bold";
        }
        setCookie(source_type + "_trackerfeed_cb_" + filter_watchlist_id.value, is_unchecked, 10000);        
    }
}

function loadEarlierObservations(author_id, qtype) {
    var loading = getElem("loading_earlier_image");
    if (loading != null) {
        loading.style.visibility = "visible";
    }
    
    var date_comp = getElem("date_comp_input");
    var date_tiebreaker = getElem("date_tiebreaker_input");
    
    if (date_comp != null) {
        date_comp_value = date_comp.value;
    }
    
    if (date_tiebreaker != null) {
        date_tiebreaker_value = date_tiebreaker.value;
    }
        
    var params = {author_id:author_id, qtype:qtype, date_comp:date_comp_value, date_tiebreaker:date_tiebreaker_value};
    var url = "/tracker/get_insights";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    var results = data.split("<!--divider-->")
                    var earlier_observations = getElem("earlier_observations");
                    if (earlier_observations != null) {
                        j(earlier_observations).append(results[0]);
                    }
                    if (date_comp != null && results.length > 1) {
                        date_comp.value = results[1];
                    }
                    if (date_tiebreaker != null && results.length > 2) {
                        date_tiebreaker.value = results[2];
                    }
                    
                    if (results.length < 2) {
                        var load_earlier_observations = getElem("load_earlier_observations");
                        if (load_earlier_observations != null) {
                            j(load_earlier_observations).hide();
                        }
                    }
                    
                    if (loading != null) {
                        loading.style.visibility = "hidden";
                    }
                    
                } else {
                    alert("Error loading observations. Please try again.");
                }
            }
   });
}

function selectObservationConnection(index, unique) {
    if (observation_connections != null && observation_connections.length > index) {
        var connection = observation_connections[index];
        setObservationDest(connection.user_id, connection.first_name + "&nbsp;" + connection.last_name, true, unique);
    }
    
    var input = getElem("observation_text_" + unique);
    if (input != null) {
        input.focus();
    }
    
}

function sortConnectionSearchResult(a,b) {
    return b.score - a.score;
}

function searchObservationContacts(event, unique) {
    if (event.keyCode == 13) {
       selectObservationConnection(currently_selected_observation_connection, unique);
       return;
    } else if (event.keyCode == 40) {
        if (currently_selected_observation_connection < observation_connections.length-1)
            currently_selected_observation_connection++;
    } else if (event.keyCode == 38) {
        if (currently_selected_observation_connection > 0)
            currently_selected_observation_connection--;        
    }
    
       // if esc key is pressed or query length is 0
    else if (event.keyCode == 27) {
       toggleObservationsDropdown(unique);
    } else {
        currently_selected_observation_connection = 0;
    }
    
    
    // get the search query
    var q = null;
    var q_node = getElem("search_contact_text_input_" + unique);
    if (q_node != null) {
        q = trim(q_node.value).toLowerCase();
    }
    
    // populate the results
    var max_to_sort = 1000;
    var max_to_show = 7;
    var connections_to_sort = new Array();
    var count = 0;
    var results = getElem("search_results_" + unique);
    if (results != null) {
        if (q != null && q != "") {
            var connection = null;
            var theHTML = new Array();
            var score = 0;
            for (var i=0; i < my_connections.length && count < max_to_sort; i++, count++) {
                
                connection = my_connections[i];
                score = 0;
                if (connection.full_name.toLowerCase().indexOf(q) >= 0) {
                    score += 2000 / (connection.full_name.toLowerCase().indexOf(q)+1);
                }
                
                if (connection.first_name.toLowerCase().indexOf(q) >= 0) {
                    score += 1000 / (connection.first_name.toLowerCase().indexOf(q)+1);
                }
                
                if (connection.last_name.toLowerCase().indexOf(q) >= 0) {
                    score += 500 / (connection.last_name.toLowerCase().indexOf(q)+1);
                }
                
                if (connection.email.toLowerCase().indexOf(q) >= 0) {
                    score += 500 / (connection.email.toLowerCase().indexOf(q)+1); 
                }
                
                if (connection.user_name.toLowerCase().indexOf(q) >= 0) {
                    score += 100 / (connection.user_name.toLowerCase().indexOf(q)+1);
                }

                if (score > 0) {
                    connection.score = score;
                    connections_to_sort[connections_to_sort.length] = connection;
                }
                
            }
                
            connections_to_sort = connections_to_sort.sort(sortConnectionSearchResult);
            observation_connections = new Array();
            var html = "";
            for (var i=0; i < max_to_show && i < connections_to_sort.length; i++) {
                connection = connections_to_sort[i];
                observation_connections[observation_connections.length] = connection;
                html = "<div onclick='javascript:setObservationDest(\"" + connection.user_id + "\", \"" + connection.first_name + "&nbsp;" + connection.last_name + "\", true, \"" + unique + "\");'";
                if (i==currently_selected_observation_connection) {
                    html += "class='option option_selected'>";
                } else {
                    html += "class='option'>";
                }
                html += connection.full_name.replace(new RegExp( "(" + q + ")", 'ig' ), "<b>$1</b>") + "</div>";                    
                theHTML[theHTML.length] = html;
            }            

            j(results).html(theHTML.join(""));
        } else {
            j(results).html("");
        }
    }
}

function setObservationDest(tag_id, tag_name, is_contact, unique) {
    var selected = getElem("selected_observation_tag_id_" + unique);
    if (selected != null) {
        j(selected).html(tag_name);
    }
    
    if (is_contact) {
        var input_field = getElem("contact_id_" + unique);
        if (input_field != null) {
            input_field.value = tag_id;
        }
        var input_field = getElem("tag_id_" + unique);
        if (input_field != null) {
            input_field.value = '-1';
        }
    } else {
        var input_field = getElem("contact_id_" + unique);
        if (input_field != null) {
            input_field.value = '-1';
        }
        var input_field = getElem("tag_id_" + unique);
        if (input_field != null) {
            input_field.value = tag_id;
        }
    }
    
    closeObservationsDropdown(unique);
    
    var input = getElem("observation_text_" + unique);
    if (input != null) {
        input.focus();
    }
    
    var note = getElem("observation_note_" + unique);
    if (note != null) {
        if (is_contact) {
            j(note).html("Note: this message will only be seen by <b>" + tag_name + "</b>.");
        } else if (tag_id == -1) {
            j(note).html("Note: this message will be seen by <b>all your connections</b> and posted to your <b>public profile</b>");
        } else if (tag_id == 0) {
            j(note).html("Note: this message will only be seen by <b>your connections</b>");
        } else if (tag_id > 0) {
            j(note).html("Note: this message will only be seen by connections tagged as <b>" + tag_name + "</b>");
        } else {
            j(note).html("");            
        }
    }
}

function toggleObservationContactSearchText(unique) {
    var fake = getElem("search_contact_faketext_" + unique);
    if (fake != null) {
        j(fake).toggle();
    }
    
    var real = getElem("search_contact_text_" + unique);
    if (real != null) {
        j(real).toggle();
    }
    
    var input = getElem("search_contact_text_input_" + unique);
    if (input != null) {
        input.value = "";
        input.focus();
    }
}


function hideObservationContactSearchText(unique) {
    var fake = getElem("search_contact_faketext_" + unique);
    if (fake != null) {
        j(fake).show();
    }
    
    var real = getElem("search_contact_text_" + unique);
    if (real != null) {
        j(real).hide();
    }
    
    var results = getElem("search_results_" + unique);
    if (results != null) {
        j(results).html("");
    }
}

function showMoreReplies(observation_id) {
    var more_replies = getElem("reply_list_more_" + observation_id);
    if (more_replies != null) {
        j(more_replies).show();
    }
    var more_replies_link = getElem("reply_list_more_link_" + observation_id);
    if (more_replies_link != null) {
        j(more_replies_link).hide();
    }
}

function toggleReplyToObservation(observation_id, unique) {
    var input = getElem("reply_input_" + observation_id);
    if (input != null) {
        j(input).toggle();
    }
    
    var reply_link = getElem("add_reply_" + observation_id);
    if (input != null && reply_link != null) {
        if (input.style.display != "none") {
            j(reply_link).hide();
            var textarea = getElem("observation_text_" + unique + "_" + observation_id);
            if (textarea != null) {
                textarea.focus();
            }
    
        } else {
            var reply_list = getElem("reply_list_" + observation_id);
            if (reply_list != null && trim(reply_list.innerHTML) != "") {
                j(reply_link).show();                
            }
        }
    }
    
    strChkTwitterDivName = "twitter_comment_options_" + unique + "_" + observation_id;
}

function replyToObservation(maxLength, parent_msg_id, unique) {
    var text = getElem("observation_text_" + unique);
    var button = getElem("observation_submit_button_" + unique)
    var length = getElem("observation_length_" + unique);
    var chk_tweet = getElem("chk_tweet_comment_" + unique);    
    
    var chk_tweet_checked = "false";
    if (chk_tweet && chk_tweet.checked)
        chk_tweet_checked = chk_tweet.checked;    
    
    if (text != null && button != null) {
        if (trim(text.value).length > 0 && trim(text.value).length <= maxLength) {
            var sending_observation = getElem("sending_observation_" + unique);
            if (sending_observation != null) {
                j(sending_observation).show();
            }
            
            var params = {text:trim(text.value), parent_msg_id:parent_msg_id, chk_tweet:chk_tweet_checked};
            var url = "/tracker/reply_to_observation";
            j.ajax({
                type: "POST",
                url: url,
                data: params, 
                cache: false,
                error:
                    function() {
                    },
                success:
                    function(data){
                        if (data != "-1") {
                            // show replies
                            var replies_container = getElem("reply_list_" + parent_msg_id);
                            if (replies_container != null) {
                                j(replies_container).show();
                                j(replies_container).append(data);
                            }
                            
                            // hide reply input
                            var reply_input = getElem("reply_input_" + parent_msg_id);
                            if (reply_input != null) {
                                j(reply_input).hide();
                            }

                            var terms = unique.split("_");
                            if (terms.length == 2 && terms[0] == "overlay") {
                                j.closeDialog();
                            } else {
                                // show fake reply input
                                var add_reply = getElem("add_reply_" + parent_msg_id);
                                if (add_reply != null) {
                                    j(add_reply).show();
                                }                                
                            }
                            
                            text.value = "";
                            if (length != null)
                                j(length).html(maxLength);
                        } else {
                            alert("Error sending reply. Please try again.");
                        }
                        if (sending_observation != null) {
                           j(sending_observation).hide();
                        }
                    }
           });
            
        }
    }
}

function sendObservation(maxLength, qtype, unique) {
    var text = getElem("observation_text_" + unique);
    var button = getElem("observation_submit_button_" + unique)
    var chk_tweet = getElem("chk_tweet_" + unique);
    var length = getElem("observation_length_" + unique);
    var tag_id = getElem("tag_id_" + unique);
    var contact_id = getElem("contact_id_" + unique);
    
    var chk_tweet_checked = "false";
    if (chk_tweet && chk_tweet.checked)
        chk_tweet_checked = chk_tweet.checked;
    
    if (text != null && button != null) {
        if (trim(text.value).length > 0 && trim(text.value).length <= maxLength) {
            var sending_observation = getElem("sending_observation_" + unique);
            if (sending_observation != null) {
                j(sending_observation).show();
            }
            var params = {text:trim(text.value), qtype:qtype, tag_id:tag_id.value, contact_id:contact_id.value, chk_tweet:chk_tweet_checked};
            var url = "/tracker/send_observation";
            j.ajax({
                type: "POST",
                url: url,
                data: params, 
                cache: false,
                error:
                    function() {
                    },
                success:
                    function(data){
                        if (data != "-1") {
                            var post_insight_confirm = getElem("post_insight_confirm");
                            if (post_insight_confirm != null) {
                                j(post_insight_confirm).fadeIn(300);
                                setTimeout(function() {
                                    j(post_insight_confirm).fadeOut(300);                                    
                                }, 2500);
                            }
                            var observation_list = getElem("observation_list");
                            if (observation_list != null) {
                                // if the currently selected filter allows it, prepend the observation
                                if ((contact_id.value <= 0 && showSelfMessagesAfterSend && !showDirectMessagesAfterSend) || (contact_id.value > 0 && (showDirectMessagesAfterSend || showSelfMessagesAfterSend))) {
                                    j(observation_list).prepend(data);
                                    var no_insights = getElem("no_insights");
                                    if (no_insights != null) {
                                        j(no_insights).hide();
                                    }
                                }
                            }
                            text.value = "";
                            text.focus();
                            if (length != null)
                                j(length).html(maxLength);
                            
                            var earlier_tracked_items = getElem("earlier_tracked_items");
                            if (earlier_tracked_items != null && (showSelfMessagesAfterSend || showDirectMessagesAfterSend)) {                                
                                getNewTrackedItems();
                            }
                        } else {
                            alert("Error sending message. Please try again.");
                        }
                        if (sending_observation != null) {
                           j(sending_observation).hide();
                        }
                        cancelShowPostInsight();
                        j.closeDialog();
                    }
           });
            
        }
    }
}

function highlightNewTrackedItem(id) {
    var f = getElem(id);
    if (f != null) {
        f.className = f.className + " mi_item_new";
        setTimeout(function() {
            unhighlightNewTrackedItem(id);
        }, 10000)    
    }    
}

function unhighlightNewTrackedItem(id) {
    var f = getElem(id);
    if (f != null) {
        f.className = f.className.replace(/mi_item_new/g, "");
    }   
}


function unHighlightNewObservation(id) {
    var f = getElem(id);
    if (f != null) {
        f.className = f.className.replace(/mi_item_new/g, "");
    }
}

function highlightNewObservation(id) {
    var f = getElem(id);
    if (f != null) {
        f.className = f.className + " mi_item_new";
        setTimeout(function() {
            unHighlightNewObservation(id);
        }, 5000)    
    }

}

function unHighlightNewFeed(id) {
    var f = getElem(id);
    if (f != null) {
        f.className = f.className.replace(/mi_item_new/g, "");
    }
}

function highlightNewFeed(id) {
    
    var newMsg = getElem(id + "_new");
    if (newMsg != null) {
        newMsg.style.display = "block";
        j("#" + id + "_new").fadeIn("200");
        setTimeout(function() {
            hideNewButton(id);
        }, 10000)    
    }
    
    
    var f = getElem(id);
    if (f != null) {
        f.className = f.className + " mi_item_new";
        setTimeout(function() {
            unHighlightNewFeed(id);
        }, 10000)    
    }

}

function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

function populateContactsAndTags(data, unique) {
    var parts = data.split("<!--divider-->");
    if (parts.length > 0) {
        var put_contacts_here = getElem("put_contacts_here");
        if (put_contacts_here != null) {
            j(put_contacts_here).html(parts[0]);
        }
    }
    
    if (parts.length > 1) {
        var tags = getElem("observation_dropdown_tags_" + unique);
        if (tags != null) {
            j(tags).html(parts[1]);
        }
    }
}

function toggleObservationsDropdown(unique) {
    var observation_dropdown_options = getElem("observation_dropdown_options_" + unique);
    if (observation_dropdown_options != null) {
        j(observation_dropdown_options).toggle();
    }
    
    if (observation_dropdown_options.style.display == "none") {
        hideObservationContactSearchText(unique);   
    } else {
        if (!contacts_downloaded) {
            var url = "/tracker/load_connections";
            j.ajax({
                type: "POST",
                url: url,
                cache: false,
                data:{unique:unique},
                error:
                    function() {
                    },
                success:
                    function(data){
                        if (data != "-1") {
                            connections_data_for_observations_dropdown = data;
                            data = data.replace(/##UNIQUE##/g, unique);
                            populateContactsAndTags(data, unique);
                        }
                    }
            });    
            contacts_downloaded = true;
        } else if (connections_data_for_observations_dropdown != null) {
            data = connections_data_for_observations_dropdown.replace(/##UNIQUE##/g, unique);
            populateContactsAndTags(data, unique);
        }
    }
}

function closeObservationsDropdown(unique) {
    var observation_dropdown_options = getElem("observation_dropdown_options_" + unique);
    if (observation_dropdown_options != null) {
        j(observation_dropdown_options).hide();
    }
    hideObservationContactSearchText(unique);
}

function imposeMaxLength(event, obj, maxlength, unique, mtype) {
    if (event != null) {
        if (event.keyCode == 27) {
            cancelShowPostInsight();
            return;
        }
        
        if (event.keyCode == 13) {
            if (mtype == "observation") {
                sendObservation(maxlength, 'all', unique);            
            } else if (mtype == "reply") {
                var msg_id = getElem("msg_id_" + unique);
                if (msg_id != null) {
                    msg_id_value = msg_id.value;
                    replyToObservation(maxlength, msg_id_value, unique);            
                }
            }
            return;
        }
    }
    
    var length = getElem("observation_length_" + unique);
    if (obj.value.length <= maxlength) {
        var button = getElem("observation_submit_button_" + unique);
        if (button != null) {
            button.className = "button_link";
        }
        if (length != null) {
            length.style.color = "#000000";
        }
    } else {
        var button = getElem("observation_submit_button_" + unique);
        if (button != null) {
            button.className = "disabled";
        }
        if (length != null) {
            length.style.color = "#CC0000";
        }
    }
    if (length != null) {
        j(length).html(maxlength - obj.value.length);
    }
    
    var shorten_urls = getElem("shorten_urls_" + unique);
    if (shorten_urls != null) {
        if (obj.value != null && has_shortenable_url(obj.value)) {
            j(shorten_urls).show();
        } else {
            j(shorten_urls).hide();
        }
    }

    

}

function filterContactsByTag(tag_id, user_name) {
    var contacts_message = getElem("contacts_message");
    if (contacts_message != null) {
        j(contacts_message).hide();
    }
    var contacts_loading = getElem("contacts_loading");
    if (contacts_loading != null) {
        j(contacts_loading).show();
    }
    var loading = getElem("loading_tag_" + tag_id);
    if (loading != null) {
        j(loading).show();
    }
    var old_item = getElem("filter_contacts_tag_" + tag_id_selected);
    if (old_item != null) {
        old_item.className = "contact_item";
    }
    var item = getElem("filter_contacts_tag_" + tag_id);
    if (item != null) {
        item.className = "contact_item_selected";
        tag_id_selected = tag_id;
    }
    
    var params = null;
    if (user_name != null)
        params = {tag_id:tag_id, user_name:user_name};
    else
        params = {tag_id:tag_id};
        
    var url = "/tracker/get_contacts_by_tag";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    data = data.split("<!--divider-->")
                    list = data[0]
                    letters = data[1]
                    var contacts_list = getElem("contacts_list");
                    if (contacts_list != null) {
                        j(contacts_list).html(list);
                    }
                    var contacts_alpha = getElem("contacts_alpha");
                    if (contacts_alpha != null) {
                        j(contacts_alpha).html(letters);
                    }
                }
                if (loading != null) {
                    j(loading).hide();
                }
                if (contacts_loading != null) {
                    j(contacts_loading).hide();
                }
            }
   });    
}

function filterContactsByGeo(geo_code, user_name) {
    var contacts_message = getElem("contacts_message");
    if (contacts_message != null) {
        j(contacts_message).hide();
    }
    var contacts_loading = getElem("contacts_loading");
    if (contacts_loading != null) {
        j(contacts_loading).show();
    }

    var loading = getElem("loading_geo_" + geo_code);
    if (loading != null) {
        j(loading).show();
    }
    var old_item = getElem("filter_contacts_geo_" + geo_code_selected);
    if (old_item != null) {
        old_item.className = "contact_item";
    }
    var item = getElem("filter_contacts_geo_" + geo_code);
    if (item != null) {
        item.className = "contact_item_selected";
        geo_code_selected = geo_code;
    }
    var params = {geo_code:geo_code, user_name:user_name};
    var url = "/tracker/get_contacts_by_geo";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    data = data.split("<!--divider-->")
                    list = data[0]
                    letters = data[1]
                    var contacts_list = getElem("contacts_list");
                    if (contacts_list != null) {
                        j(contacts_list).html(list);
                    }
                    var contacts_alpha = getElem("contacts_alpha");
                    if (contacts_alpha != null) {
                        j(contacts_alpha).html(letters);
                    }
                }
                if (loading != null) {
                    j(loading).hide();
                }
                if (contacts_loading != null) {
                    j(contacts_loading).hide();
                }
            }
   });    
}


function filterContactsByIndustry(industry_id, user_name) {
    var contacts_message = getElem("contacts_message");
    if (contacts_message != null) {
        j(contacts_message).hide();
    }
    var contacts_loading = getElem("contacts_loading");
    if (contacts_loading != null) {
        j(contacts_loading).show();
    }

    var loading = getElem("loading_industry_" + industry_id);
    if (loading != null) {
        j(loading).show();
    }
    var old_item = getElem("filter_contacts_industry_" + industry_id_selected);
    if (old_item != null) {
        old_item.className = "contact_item";
    }
    var item = getElem("filter_contacts_industry_" + industry_id);
    if (item != null) {
        item.className = "contact_item_selected";
        industry_id_selected = industry_id;
    }
    var params = {industry_id:industry_id, user_name:user_name};
    var url = "/tracker/get_contacts_by_industry";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    data = data.split("<!--divider-->")
                    list = data[0]
                    letters = data[1]
                    var contacts_list = getElem("contacts_list");
                    if (contacts_list != null) {
                        j(contacts_list).html(list);
                    }
                    var contacts_alpha = getElem("contacts_alpha");
                    if (contacts_alpha != null) {
                        j(contacts_alpha).html(letters);
                    }
                }
                if (loading != null) {
                    j(loading).hide();
                }
                if (contacts_loading != null) {
                    j(contacts_loading).hide();
                }
            }
   });    
}


function getContact(contact_id) {
    var contacts_message = getElem("contacts_message");
    if (contacts_message != null) {
        j(contacts_message).hide();
    }
    var contacts_loading = getElem("contacts_loading");
    if (contacts_loading != null) {
        j(contacts_loading).show();
    }

    var loading = getElem("loading_contact_" + contact_id);
    if (loading != null) {
        j(loading).show();
    }
    var old_item = getElem("contact_item_" + contact_id_selected);
    if (old_item != null) {
        old_item.className = "contact_item";
    }
    var item = getElem("contact_item_" + contact_id);
    if (item != null) {
        item.className = "contact_item_selected";
        contact_id_selected = contact_id;
    }
    var params = {contact_id:contact_id};
    var url = "/tracker/get_contact";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    var contact_details = getElem("contact_details");
                    if (contact_details != null) {
                        j(contact_details).html(data);
                    }
                }
                if (loading != null) {
                    j(loading).hide();
                }
                if (contacts_loading != null) {
                    j(contacts_loading).hide();
                }
            }
   });
}

function removeTagFromContact(tag_id, contact_id) {
    var contacts_message = getElem("contacts_message");
    if (contacts_message != null) {
        j(contacts_message).hide();
    }
    var contacts_loading = getElem("contacts_loading");
    if (contacts_loading != null) {
        j(contacts_loading).show();
    }

    var remove = getElem("remove_tag_" + tag_id + "_" + contact_id);
    if (remove != null) {
        j(remove).html("<span style='color:#BBBBBB;font-style:italic;font-size:0.90em'>removing...</span>");
    }
    var params = {tag_id:tag_id, contact_id:contact_id};
    var url = "/tracker/remove_tag_from_contact";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    var contact_details_tag_list = getElem("contact_details_tag_list_" + contact_id);
                    if (contact_details_tag_list != null) {
                        j(contact_details_tag_list).html(data);
                    }
                    if (contacts_loading != null) {
                        j(contacts_loading).hide();
                    }
                }
            }
   });    
}

function addTagToContact(tag_id, contact_id) {
    var contacts_message = getElem("contacts_message");
    if (contacts_message != null) {
        j(contacts_message).hide();
    }
    var contacts_loading = getElem("contacts_loading");
    if (contacts_loading != null) {
        j(contacts_loading).show();
    }
    var remove = getElem("add_tag_" + tag_id + "_" + contact_id);
    if (remove != null) {
        j(remove).html("<span style='color:#BBBBBB;font-style:italic;font-size:0.90em'>adding...</span>");
    }
    var params = {tag_id:tag_id, contact_id:contact_id};
    var url = "/tracker/add_tag_to_contact";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    var contact_details_tag_list = getElem("contact_details_tag_list_" + contact_id);
                    if (contact_details_tag_list != null) {
                        j(contact_details_tag_list).html(data);
                    }
                    if (contacts_loading != null) {
                        j(contacts_loading).hide();
                    }
                }
            }
   });    
}


function removeContact(contact_id) {
    var c = window.confirm("Are you sure you want to remove this contact?");
    if (!c)
        return;
    
    var contacts_message = getElem("contacts_message");
    if (contacts_message != null) {
        j(contacts_message).hide();
    }
    var contacts_loading = getElem("contacts_loading");
    if (contacts_loading != null) {
        j(contacts_loading).show();
    }
    var params = {contact_id:contact_id};
    var url = "/tracker/remove_contact";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    var contacts_list = getElem("contacts_list");
                    if (contacts_list != null) {
                        j(contacts_list).html(data);
                    }
                    var contact_details = getElem("contact_details");
                    if (contact_details != null) {
                        j(contact_details).html("");
                    }
                    if (contacts_loading != null) {
                        j(contacts_loading).hide();
                    }
                    selectContactsFilter("all", null);
                }
            }
   });
}

function sendConnectionInvitation(contact_id) {
    var invites_loading = getElem("invites_loading");
    if (invites_loading != null) {
        j(invites_loading).show();
    }
    
    var msg_text = '';
    var message = getElem("invite_contact_overlay_message");
    if (message != null) {
        msg_text = message.value;
    }
    
    var send_invite_connection = getElem("send_invite_connection");
    if (send_invite_connection != null) {
        j(send_invite_connection).hide();
    }
    
    var sending_invite_connection = getElem("sending_invite_connection");
    if (sending_invite_connection != null) {
        j(sending_invite_connection).show();
    }
    
    tags_selected = "";
    for (i=0;i<document.overlay_invite_form.tags.length;i++) {
        if (document.overlay_invite_form.tags[i].checked) {
            if (tags_selected != "") {
                 tags_selected += ",";
            }
            tags_selected += document.overlay_invite_form.tags[i].value;
        }
    }

    var params = {contact_id:contact_id, message:msg_text, tags_list:tags_selected};
    var url = "/tracker/do_send_connection_invitation";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    if (sending_invite_connection != null) {
                        j(sending_invite_connection).html("Invitation Sent!");
                    }
                    setTimeout(function() {
                        j.closeDialog();
                    }, 250);
                }
            }
   });
}

function toggleFullMsg(msgId) {
    var msg_clipped = getElem('msg_clipped_' + msgId);
    if (msg_clipped != null) {
        j(msg_clipped).toggle();
    }
    
    var msg_full = getElem('msg_full_' + msgId);
    if (msg_full != null) {
        j(msg_full).toggle();
    }
}

function acceptContactInvitation(contact_id) {
    
    var loading = getElem("accept_" + contact_id);
    if (loading != null) {
        j(loading).html("Accepting...");
    }
    var loading = getElem("archive_" + contact_id);
    if (loading != null) {
        j(loading).hide();
    }
    var params = {contact_id:contact_id};
    var url = "/tracker/accept_contact_invitation";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    if (loading != null) {
                        j(loading).hide();                            
                    }
                    var loading = getElem("accept_" + contact_id);
                    if (loading != null) {
                        j(loading).hide();
                    }
                   var accepted = getElem("accepted_" + contact_id);
                    if (accepted != null) {
                        j(accepted).show();                            
                    }
                    var invite = getElem("invite_" + contact_id);
                    if (invite != null) {
                        invite.className = "contact_invitee";                           
                    }
                    
                } else {
                    if (loading != null) {
                        j(loading).html("<span class='market_down>Contact not added.</span>");
                    }                    
                }
            }
   });
}


function archiveContactInvitation(contact_id) {
    
    setTimeout(function() {
        var row = getElem("row_" + contact_id);
        if (row != null) {
            j(row).fadeOut(250);
        }
    }, 200);

    var loading = getElem("archive_" + contact_id);
    //if (loading != null) {
    //    j(loading).html("Archiving...");
    //}
    var params = {contact_id:contact_id};
    var url = "/tracker/archive_contact_invitation";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    /*
                    if (loading != null) {
                        j(loading).hide();                            
                    }
                    var archived = getElem("archived_" + contact_id);
                    if (archived != null) {
                        j(archived).show();                            
                    }
                    */
                } else {
                    if (loading != null) {
                        j(loading).html("<span class='market_down>Contact not archived.</span>");
                    }                    
                }
            }
   });
}

function composeInvite() {
    doInviteConnectionTabs('compose');
    doInviteConnectionContents('compose');
    var browse = getElem("browse_contacts_section");
    if (browse != null) {
        j(browse).hide();
    }
    
    var imp = getElem("import_contacts_section");
    if (imp != null) {
        j(imp).hide();
    }
    
    var invite = getElem("invite_contacts_section");
    if (invite != null) {
        j(invite).show();
    }
}

function getInvites(type, page) {
    doInviteConnectionTabs(type);
    doInviteConnectionContents(type, page);

    var browse = getElem("browse_contacts_section");
    if (browse != null) {
        j(browse).hide();
    }
    
    var imp = getElem("import_contacts_section");
    if (imp != null) {
        j(imp).hide();
    }
    
    var invite = getElem("invite_contacts_section");
    if (invite != null) {
        j(invite).show();
    }
    
}

function doInviteConnectionTabs(type) {
    selectContactsFilter('');
    var invite_ids = ["filter_contacts_invite_compose", "filter_contacts_invite_received", "filter_contacts_invite_sent", "filter_contacts_invite_archived"];
    for (i in invite_ids) {
        var old_item = getElem(invite_ids[i]);
        if (old_item != null) {
            old_item.className = "intranav_dark"
        }
    }
    
    var item = getElem("filter_contacts_invite_" + type);
    if (item != null) {
        item.className = "intranav_dark intranav_dark_selected";
    }
    
}

function doInviteConnectionContents(type, page) {
    var contacts_message = getElem("contacts_message");
    if (contacts_message != null) {
        j(contacts_message).hide();
    }
    var contacts_loading = getElem("contacts_loading");
    if (contacts_loading != null) {
        j(contacts_loading).show();
    }

    var loading = getElem("loading_invite_" + type);
    if (loading != null) {
        j(loading).show();
    }

    var invite_ids = ["contacts_invite_import_section", "contacts_invite_compose_section", "contacts_invite_received_section", "contacts_invite_sent_section", "contacts_invite_archived_section"];
    for (i in invite_ids) {
        var old_item = getElem(invite_ids[i]);
        if (old_item != null) {
            j(old_item).hide();
        }
    }
    
    var item = getElem("contacts_invite_" + type + "_section");
    if (item != null) {
        j(item).show();
    }
    
    if (page == null) {
        page = 1;
    }

    if (type == "sent" || type == "received" || type == "archived") {
        var params = {folder:type, page:page};
        var url = "/tracker/mymessages/";
        j.ajax({
            type: "POST",
            url: url,
            data: params, 
            cache: false,
            error:
                function() {
                },
            success:
                function(data){
                    if (data != "-1") {
                        var content = getElem("contacts_invite_" + type + "_section");
                        if (content != null) {
                            j(content).html(data);
                        }
                    }
                    if (loading != null) {
                        j(loading).hide();
                    }
                    if (contacts_loading != null) {
                        j(contacts_loading).hide();
                    }
                }
       });
    } else {
        if (loading != null) {
            j(loading).hide();
        }
        if (contacts_loading != null) {
            j(contacts_loading).hide();
        }
    }
}


function selectContactsFilter(type, user_name) {
    var tab_ids = ["all_contacts", "tag_contacts", "industry_contacts", "geo_contacts", "invite_contacts", "import_contacts"];
    
    if (type != '')
        doInviteConnectionTabs('');

    
    if (type == "import") {
        var browse = getElem("browse_contacts_section");
        if (browse != null) {
            j(browse).hide();
        }
        var invite = getElem("invite_contacts_section");
        if (invite != null) {
            j(invite).hide();
        }
        var imp = getElem("import_contacts_section");
        if (imp != null) {
            j(imp).show();
        }
    } else if (type == "invite") {
        var browse = getElem("browse_contacts_section");
        if (browse != null) {
            j(browse).hide();
        }
        var invite = getElem("invite_contacts_section");
        if (invite != null) {
            j(invite).show();
        }
        var imp = getElem("import_contacts_section");
        if (imp != null) {
            j(imp).hide();
        }
    } else {
        var browse = getElem("browse_contacts_section");
        if (browse != null) {
            j(browse).show();
        }
        var invite = getElem("invite_contacts_section");
        if (invite != null) {
            j(invite).hide();
        }
        var imp = getElem("import_contacts_section");
        if (imp != null) {
            j(imp).hide();
        }
    }
    
    for (tab in tab_ids) {
        var t = getElem(tab_ids[tab]);
        if (t != null) {
            t.className = "intranav_dark";
        }
        var l = getElem(tab_ids[tab] + "_link");
        if (l != null) {
            l.className = "";
        }
        var items = getElem(tab_ids[tab] + "_list");
        if (items != null) {
            j(items).hide();
        }
    }
    
    var selected = getElem(type + "_contacts");
    if (selected != null) {
        selected.className = "intranav_dark intranav_dark_selected";
    }

    var selected_link = getElem(type + "_contacts_link");
    if (selected_link != null) {
        selected_link.className = "nolink";
    }

    var selected_items = getElem(type + "_contacts_list");
    if (selected_items != null) {
        j(selected_items).show();
    }
    
    if (type == "all") {
        filterContactsByTag(-1, user_name);
    }
}

function showCreateNewWatchlistDialog() {
    var new_watchlist_options = getElem("new_watchlist_options");
    if (new_watchlist_options != null) {
        j(new_watchlist_options).toggle();
    
        if (new_watchlist_options.style.display != "none") {
            var link = getElem("new_watchlist_link");
            if (link != null) {
                link.className = "firehose_filter_link_tab";
            }
            
        } else {
            var link = getElem("new_watchlist_link");
            if (link != null) {
                link.className = "novisited emkcart";
            }
    
        }


    }
    
}


function toggleWatchlistOptions(watchlist_id) {
    var options = getElem("watchlist_options_links_" + watchlist_id);
    if (options != null) {
        j(options).toggle();
    }
}

function toggleWatchlistOptionsLink(watchlist_id) {
    var options = getElem("watchlist_options_link_" + watchlist_id);
    if (options != null) {
        j(options).toggle();
    }
}

function doNewWatchlistSelectTag() {
    tag_selected = false;
    for (i=0;i<document.newWatchlistOptionsForm.watchlist_sharing_tag.length;i++) {
        if (document.newWatchlistOptionsForm.watchlist_sharing_tag[i].checked) {
            tag_selected = true;
        }
    }
    
    if (tag_selected) {
        document.newWatchlistOptionsForm.watchlist_sharing_all.checked = false;
    } else {
        document.newWatchlistOptionsForm.watchlist_sharing_all.checked = true;        
    }
}

function doNewWatchlistSelectAll() {
    var all_checked = document.newWatchlistOptionsForm.watchlist_sharing_all.checked;
    if (all_checked) {
        for (i=0;i<document.newWatchlistOptionsForm.watchlist_sharing_tag.length;i++) {
            document.newWatchlistOptionsForm.watchlist_sharing_tag[i].checked = false;
        }
    }
}

function doNewWatchlistOptions() {
    var watchlist_type = "company"
    for (i=0;i<document.newWatchlistOptionsForm.watchlist_type.length;i++) {
        if (document.newWatchlistOptionsForm.watchlist_type[i].checked)  {
            watchlist_type = document.newWatchlistOptionsForm.watchlist_type[i].value;
        }
    }
    
    var labels = ["company", "person", "industry"];
    
    for (var x in labels) {
        var label = getElem("new_watchlist_" + labels[x] + "_label");
        if (label != null) {
            label.className = "filter_firehose_section_notselected";
        }
    }
    
    var selected_label = getElem("new_watchlist_" + watchlist_type + "_label");
    if (selected_label != null) {
        selected_label.className = "filter_firehose_section_selected";    
    }


    var watchlist_sharing_group = "public"
    for (i=0;i<document.newWatchlistOptionsForm.watchlist_sharing_group.length;i++) {
        if (document.newWatchlistOptionsForm.watchlist_sharing_group[i].checked)  {
            watchlist_sharing_group = document.newWatchlistOptionsForm.watchlist_sharing_group[i].value;
        }
    }
    
    var groups = ["public", "shared", "private"];
    
    for (var x in groups) {
        var group = getElem("new_watchlist_" + groups[x] + "_label");
        if (group != null) {
            group.className = "filter_firehose_section_notselected";
        }
    }
    
    var selected_group = getElem("new_watchlist_" + watchlist_sharing_group + "_label");
    if (selected_group != null) {
        selected_group.className = "filter_firehose_section_selected";    
    }
    
    for (i=0;i<document.newWatchlistOptionsForm.watchlist_sharing_tag.length;i++) {
        var watchlist_sharing_tag = getElem("new_watchlist_tag_" + document.newWatchlistOptionsForm.watchlist_sharing_tag[i].value);
        if (watchlist_sharing_tag != null) {
            if (watchlist_sharing_group != "shared") {
                var new_watchlist_connection_tags = getElem("new_watchlist_connection_tags");
                if (new_watchlist_connection_tags != null) {
                    j(new_watchlist_connection_tags).slideUp(250);
                }
                watchlist_sharing_tag.className = "disabled";
                document.newWatchlistOptionsForm.watchlist_sharing_tag[i].disabled = true;
            } else {
                var new_watchlist_connection_tags = getElem("new_watchlist_connection_tags");
                if (new_watchlist_connection_tags != null) {
                    j(new_watchlist_connection_tags).slideDown(250);
                }
                watchlist_sharing_tag.className = "";
                document.newWatchlistOptionsForm.watchlist_sharing_tag[i].disabled = false;
            }
        }
    }
    var watchlist_sharing_tag_all = getElem("new_watchlist_tag_-1");
    if (watchlist_sharing_group != "shared") {
        watchlist_sharing_tag_all.className = "disabled";
        document.newWatchlistOptionsForm.watchlist_sharing_all.disabled = true;
    } else {
        watchlist_sharing_tag_all.className = "";
        document.newWatchlistOptionsForm.watchlist_sharing_all.disabled = false;
    }
}


function doEditWatchlistSharingSelectTag(watchlist_id) {
    tag_selected = false;
    for (i=0;i<eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_tag.length");i++) {
        if (eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_tag[i].checked")) {
            tag_selected = true;
        }
    }
    
    if (tag_selected) {
        eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_all.checked = false");
    } else {
        eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_all.checked = true");
    }
}

function doEditWatchlistSharingSelectAll(watchlist_id) {
    var all_checked = eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_all.checked");
    if (all_checked) {
        for (i=0;i<eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_tag.length");i++) {
            eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_tag[i].checked = false");
        }
    }
}


function doEditWatchlistSharingOptions(watchlist_id) {

    var watchlist_sharing_group = "public"
    for (i=0;i<eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_group.length");i++) {
        if (eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_group[i].checked"))  {
            watchlist_sharing_group = eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_group[i].value");
        }
    }
    
    var groups = ["public", "shared", "private"];
    
    for (var x in groups) {
        var group = getElem("new_watchlist_" + groups[x] + "_label_" + watchlist_id);
        if (group != null) {
            group.className = "filter_firehose_section_notselected";
        }
    }
    
    var selected_group = getElem("new_watchlist_" + watchlist_sharing_group + "_label_" + watchlist_id);
    if (selected_group != null) {
        selected_group.className = "filter_firehose_section_selected";    
    }
    
    for (i=0;i<eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_tag.length");i++) {
        var watchlist_sharing_tag = getElem("new_watchlist_tag_" + eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_tag[i].value") + "_" + watchlist_id);
        if (watchlist_sharing_tag != null) {
            if (watchlist_sharing_group != "shared") {
                var new_watchlist_connection_tags = getElem("new_watchlist_connection_tags_" + watchlist_id);
                if (new_watchlist_connection_tags != null) {
                    j(new_watchlist_connection_tags).slideUp(250);
                }
                watchlist_sharing_tag.className = "disabled";
                eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_tag[i].disabled = true");
            } else {
                var new_watchlist_connection_tags = getElem("new_watchlist_connection_tags_" + watchlist_id);
                if (new_watchlist_connection_tags != null) {
                    j(new_watchlist_connection_tags).slideDown(250);
                }
                watchlist_sharing_tag.className = "";
                eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_tag[i].disabled = false");
            }
        }
    }
    var watchlist_sharing_tag_all = getElem("new_watchlist_tag_-1_" + watchlist_id);
    if (watchlist_sharing_group != "shared") {
        watchlist_sharing_tag_all.className = "disabled";
        eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_all.disabled = true");
    } else {
        watchlist_sharing_tag_all.className = "";
        eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_all.disabled = false");
    }
}


function submitCreateNewWatchlist() {
    var watchlist_name = document.newWatchlistOptionsForm.watchlist_name.value;
    if (watchlist_name == "") {
        alert("Name cannot be blank.");
        return;
    }
    if (watchlist_name.length > 25) {
        alert("Name cannot exceed 25 characters");
        return;
    }
    
    var watchlist_type = "";
    for (i=0;i<document.newWatchlistOptionsForm.watchlist_type.length;i++) {
        if (document.newWatchlistOptionsForm.watchlist_type[i].checked)  {
            watchlist_type = document.newWatchlistOptionsForm.watchlist_type[i].value;
        }
    }
    if (watchlist_type == "") {
        alert("Please choose a type of watchlist.");
        return;
    }
    
    var watchlist_sharing_group = "";
    for (i=0;i<document.newWatchlistOptionsForm.watchlist_sharing_group.length;i++) {
        if (document.newWatchlistOptionsForm.watchlist_sharing_group[i].checked)  {
            watchlist_sharing_group = document.newWatchlistOptionsForm.watchlist_sharing_group[i].value;
        }
    }
    if (watchlist_sharing_group == "") {
        alert("Please choose a sharing option.");
        return;
    }
    
    var watchlist_sharing_tag_ids = "";
    if (watchlist_sharing_group == "shared") {
        for (i=0;i<document.newWatchlistOptionsForm.watchlist_sharing_tag.length;i++) {
            if (document.newWatchlistOptionsForm.watchlist_sharing_tag[i].checked) {
                if (watchlist_sharing_tag_ids != "") {
                     watchlist_sharing_tag_ids += ",";
                }
                watchlist_sharing_tag_ids += document.newWatchlistOptionsForm.watchlist_sharing_tag[i].value;
            }
        }
        if (document.newWatchlistOptionsForm.watchlist_sharing_all.checked) {
            if (watchlist_sharing_tag_ids != "") {
                 watchlist_sharing_tag_ids += ",";
            }
            watchlist_sharing_tag_ids += document.newWatchlistOptionsForm.watchlist_sharing_all.value;
        }
    }
    
    if (watchlist_sharing_group == "shared" && watchlist_sharing_tag_ids == "") {
        alert("If you are choosing to share your tracker, please choose either 'All connections' or at least one tag");
        return;
    }
    
    var loading = getElem("watchlist_loading");
    if (loading != null) {
        j(loading).show();
    }
    showCreateNewWatchlistDialog();
    var params = {watchlist_type:watchlist_type, watchlist_name:watchlist_name, watchlist_sharing_group:watchlist_sharing_group, watchlist_sharing_tag_ids:watchlist_sharing_tag_ids};
    var url = "/tracker/create_watchlist";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    var sortable_watchlists = getElem("sortable_watchlists");
                    if (sortable_watchlists != null) {
                        j(sortable_watchlists).prepend(data);
                    }
                    if (loading != null) {
                        j(loading).hide();
                    }
                }
            }
   });
}



function submitCreateNewWatchlistT2Dot0() {
    var watchlist_name = document.newWatchlistOptionsForm.watchlist_name.value;
    if (watchlist_name == "") {
        alert("Name cannot be blank.");
        return;
    }
    if (watchlist_name.length > 25) {
        alert("Name cannot exceed 25 characters");
        return;
    }
    
    var watchlist_type = "";
    for (i=0;i<document.newWatchlistOptionsForm.watchlist_type.length;i++) {
        if (document.newWatchlistOptionsForm.watchlist_type[i].checked)  {
            watchlist_type = document.newWatchlistOptionsForm.watchlist_type[i].value;
        }
    }
    if (watchlist_type == "") {
        var wtype = getElem("create_watchlist_overlay_watchlist_type");
        if (wtype != null) {
            watchlist_type = wtype.value;
        }
    }
    
    if (watchlist_type == "") {
        alert("Please choose a type of watchlist.");
        return;
    }
    
    var watchlist_sharing_group = "";
    for (i=0;i<document.newWatchlistOptionsForm.watchlist_sharing_group.length;i++) {
        if (document.newWatchlistOptionsForm.watchlist_sharing_group[i].checked)  {
            watchlist_sharing_group = document.newWatchlistOptionsForm.watchlist_sharing_group[i].value;
        }
    }
    if (watchlist_sharing_group == "") {
        alert("Please choose a sharing option.");
        return;
    }
    
    var watchlist_sharing_tag_ids = "";
    if (watchlist_sharing_group == "shared") {
        for (i=0;i<document.newWatchlistOptionsForm.watchlist_sharing_tag.length;i++) {
            if (document.newWatchlistOptionsForm.watchlist_sharing_tag[i].checked) {
                if (watchlist_sharing_tag_ids != "") {
                     watchlist_sharing_tag_ids += ",";
                }
                watchlist_sharing_tag_ids += document.newWatchlistOptionsForm.watchlist_sharing_tag[i].value;
            }
        }
        if (document.newWatchlistOptionsForm.watchlist_sharing_all.checked) {
            if (watchlist_sharing_tag_ids != "") {
                 watchlist_sharing_tag_ids += ",";
            }
            watchlist_sharing_tag_ids += document.newWatchlistOptionsForm.watchlist_sharing_all.value;
        }
    }
    
    if (watchlist_sharing_group == "shared" && watchlist_sharing_tag_ids == "") {
        alert("If you are choosing to share your tracker, please choose either 'All connections' or at least one tag");
        return;
    }
    
    var entity_id = -1;
    var entity_id_input = getElem("create_watchlist_entity_id_to_add");
    if (entity_id_input != null) {
        entity_id = entity_id_input.value;
    }
    
    var loading = getElem("watchlist_loading");
    if (loading != null) {
        j(loading).show();
    }
    
    var create_watchlist_button = getElem("create_watchlist_button");
    if (create_watchlist_button != null) {
        create_watchlist_button.disabled = true;
    }

    var params = {overlay:1, entity_id:entity_id, watchlist_type:watchlist_type, watchlist_name:watchlist_name, watchlist_sharing_group:watchlist_sharing_group, watchlist_sharing_tag_ids:watchlist_sharing_tag_ids};
    var url = "/tracker/create_watchlist";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    setCookie("tracker2dot0_msg", "Watchlist created", 10000);
                    if (entity_id > 0) {
                        window.location.reload();
                    } else {
                        window.location = '/my/tracker/?fid=' + data;
                    }
                }
            }
   });
}


function submitEditWatchlist(watchlist_type, watchlist_id) {
    var watchlist_name = eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_name.value");
    if (watchlist_name == "") {
        alert("Name cannot be blank.");
        return;
    }
    if (watchlist_name.length > 25) {
        alert("Name cannot exceed 25 characters");
        return;
    }

    var watchlist_sharing_group = "";
    for (i=0;i<eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_group.length");i++) {
        if (eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_group[i].checked"))  {
            watchlist_sharing_group = eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_group[i].value");
        }
    }
    if (watchlist_sharing_group == "") {
        alert("Please choose a sharing option.");
        return;
    }
    
    var watchlist_sharing_tag_ids = "";
    if (watchlist_sharing_group == "shared") {
        for (i=0;i<eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_tag.length");i++) {
            if (eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_tag[i].checked")) {
                if (watchlist_sharing_tag_ids != "") {
                     watchlist_sharing_tag_ids += ",";
                }
                watchlist_sharing_tag_ids += eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_tag[i].value");
            }
        }
        if (eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_all.checked")) {
            if (watchlist_sharing_tag_ids != "") {
                 watchlist_sharing_tag_ids += ",";
            }
            watchlist_sharing_tag_ids += eval("document.editWatchlistSharingOptionsForm_" + watchlist_id + ".watchlist_sharing_all.value");
        }
    }
    
    if (watchlist_sharing_group == "shared" && watchlist_sharing_tag_ids == "") {
        alert("If you are choosing to share your tracker, please choose either 'All connections' or at least one tag");
        return;
    }
    
    var loading = getElem("watchlist_loading_" + watchlist_id);
    if (loading != null) {
        j(loading).show();
    }

    toggleEditSharing(watchlist_type, watchlist_id);
    
    var params = {watchlist_id:watchlist_id, watchlist_name:watchlist_name, watchlist_type:watchlist_type, watchlist_sharing_group:watchlist_sharing_group, watchlist_sharing_tag_ids:watchlist_sharing_tag_ids};
    var url = "/tracker/edit_watchlist";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
            },
        success:
            function(data){
                if (data != "-1") {
                    if (loading != null) {
                        j(loading).hide();
                    }
                    
                    var name = getElem("watchlist_name_" + watchlist_id);
                    if (name != null) {
                        j(name).html(watchlist_name);
                    }

                    var img = getElem("watchlist_shared_icon_" + watchlist_id);
                    if (img != null) {
                        img.src = img.src.replace(/status_public.png/g,"status_" + watchlist_sharing_group + ".png");
                        img.src = img.src.replace(/status_private.png/g,"status_" + watchlist_sharing_group + ".png");
                        img.src = img.src.replace(/status_shared.png/g,"status_" + watchlist_sharing_group + ".png");
                    }

                    var text = getElem("watchlist_shared_text_" + watchlist_id);
                    if (text != null) {
                        j(text).html(watchlist_sharing_group);
                    }
                    
                    var msg = getElem("watchlist_privacy_msg_" + watchlist_id);
                    if (msg != null) {
                        j(msg).show();
                        msg.style.display = "inline";
                        j(msg).html(watchlist_name + " is now " + watchlist_sharing_group);
                        if (watchlist_sharing_group == "private") {
                            j(msg).append(". Only you see it.");
                        } else {
                            j(msg).append(" on your profile.");
                        }
                        
                        setTimeout(function() {
                            var msg = getElem("watchlist_privacy_msg_" + watchlist_id);
                            j(msg).fadeOut();
                        }, 3000);
                    }

                } else {
                    if (loading != null) {
                        j(loading).hide();
                    }
                    alert("Oops. Couldn't edit watchlist. Try again.");
                }
            }
   });
}


function submitEditWatchlistName(watchlist_id) {

    toggleWatchlistRenameLoading(watchlist_id);

    var watchlist_name = null;
    var rename_input = getElem("watchlist_rename_input_" + watchlist_id);
    if (rename_input != null) {
        watchlist_name = rename_input.value;
    }

    if (watchlist_name != null) {
        var params = {watchlist_id:watchlist_id, watchlist_name:watchlist_name};
        var url = "/tracker/edit_watchlist_name";
        j.ajax({
            type: "POST",
            url: url,
            data: params, 
            cache: false,
            error:
                function() {
                },
            success:
                function(data){
                    if (data != "-1") {
                        
                        toggleWatchlistRenameLoading(watchlist_id);
                        
                        var name = getElem("watchlist_name_" + watchlist_id);
                        if (name != null) {
                            j(name).html(watchlist_name);
                        }
                        
                        toggleWatchlistRenameInput(watchlist_id);
    
                    } else {
                        toggleWatchlistRenameLoading(watchlist_id);
                        
                        alert("Oops. Couldn't edit watchlist name. Try again.");
                    }
                }
       });
    }
}


function clearTrackerMsg() {
    setCookie("tracker2dot0_msg", "", 10000);
    var t2dot0_global_msg_text = getElem("t2dot0_global_msg_text");
    if (t2dot0_global_msg_text != null) {
        j(t2dot0_global_msg_text).hide();
    }
}


function deleteWatchlist(watchlist_type, watchlist_id) {
    var options = getElem("watchlist_options_links_" + watchlist_id);
    if (options != null) {
        j(options).hide();
    }

    var c = window.confirm("Are you sure you want to delete this " + watchlist_type + " watchlist and all of its items? This cannot be undone.");
    if (!c) {
        return;
    }
    
    var loading = getElem("watchlist_loading_" + watchlist_id);
    if (loading != null) {
        j(loading).show();
    }

    var params = {watchlist_id:watchlist_id};
    var url = "/tracker/delete_watchlist";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
                alert("Problem deleting watchlist.");
                if (loading != null) {
                    j(loading).hide();
                }
            },
        success:
            function(data){
                if (data != "-1") {
                    var results = data.split("<!--divider-->");
                    var all_watchlists_filter_id = results[0];
                    /*
                    var tracker = getElem("my_" + watchlist_type + "_watchlist_section_" + watchlist_id);
                    if (tracker != null) {
                        j(tracker).hide();
                    }
                    */
                    setCookie("tracker2dot0_msg", "Watchlist deleted", 10000);
                    window.location = "/my/tracker/?fid=" + all_watchlists_filter_id;

                } else {
                    alert("Problem deleting watchlist.");
                }
                /*
                if (loading != null) {
                    j(loading).hide();
                }
                */
            }
   });
}

function shortenUrls(unique, maxLength, otype) {
    var text_value = null;
    var text = getElem("observation_text_" + unique);
    if (text != null) {
        text_value = text.value;
    }

    if (text_value == null) {
        return;
    } else {
        j(text).hide();
    }
    
    var fake_input = getElem("fake_observation_text_" + unique);
    if (fake_input != null) {
        j(fake_input).show();
        //j(fake_input).html(text_value);
        j(fake_input).html("shortening urls...");
    }

    var message = getElem("shorten_urls_" + unique);
    if (message != null) {
        j(message).hide();
    }
    var loading = getElem("shorten_urls_loading_" + unique);
    if (loading != null) {
        j(loading).show();
    }
    
    var url = "/api/shorten_urls";
    var params = {text:text_value};
    j.ajax({
        type: "POST",
        url: url,
        data: params,
        cache: false,
        error:
            function() {
                alert("Oops. Unable to shorten URLs");
            },
        success:
            function(data){
                if (data != "-1") {
                    if (text != null) {
                        text.value = data;
                    }
                    var done = getElem("shorten_urls_done_" + unique);
                    if (done != null) {
                        j(done).show();
                        setTimeout(function() {
                            j(done).slideUp();
                        }, 1500);
                    }
                }
                    
                if (fake_input != null) {
                    j(fake_input).hide();
                }
                
                if (loading != null) {
                    j(loading).hide();
                }
                
                if (text != null) {
                    j(text).show();
                }
                
                imposeMaxLength(null, text, maxLength, unique, otype);
            }
    });
    
}

function toggleEditSharing(watchlist_type, watchlist_id) {
    var t2dot0_add = getElem("t2dot0_watchlist_add_" + watchlist_id);
    if (t2dot0_add != null) {
        j(t2dot0_add).hide();
    }

    var edit_watchlist_sharing = getElem("edit_watchlist_sharing_" + watchlist_id);
    if (edit_watchlist_sharing != null) {
        j(edit_watchlist_sharing).toggle();
    }
    var add_input = getElem("add_" + watchlist_type + "_input_" + watchlist_id);
    if (add_input != null) {
        j(add_input).hide();
    }

    var options = getElem("watchlist_options_links_" + watchlist_id);
    if (options != null) {
        j(options).hide();
    }

    var allIndustries = getElem("all_industries_" + watchlist_id);
    if (allIndustries != null) {
        j(allIndustries).hide();
    }

}

function toggleActionsTracked(feed_id) {
    var actions = getElem("actions_tracked_" + feed_id);
    if (actions != null) {
        j(actions).toggle();
    }
}


function doShowPostInsight(unique) {
    var post_insight_link = getElem("post_insight_link");
    if (post_insight_link != null) {
        post_insight_link.className = "selected_item_2";
    }
    
    var post_insight_content = getElem("post_insight_content");
    if (post_insight_content != null) {
        j(post_insight_content).show();
    }
    
    var observation_text = getElem("observation_text_nav");
    if (observation_text != null) {
        observation_text.focus();
    }
}

function cancelShowPostInsight() {
    var post_insight_link = getElem("post_insight_link");
    if (post_insight_link != null) {
        post_insight_link.className = "post_insight";
    }
    var post_insight_content = getElem("post_insight_content");
    if (post_insight_content != null) {
        j(post_insight_content).hide();
    }
}

function doShortCuts(event) {
    if (!event)
        event=window.event;

    if ((event.charCode) && (event.keyCode==0))
        code = event.charCode;
    else
        code = event.keyCode;
    
    if (code == 105) { // do insights
        if (!(event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement))
            doShowPostInsight('nav');
    } else if (code == 27) {
        cancelShowPostInsight();   
    }
}

function toggleClickToUploadPhoto() {
    var click = getElem("clickToUploadPhoto");
    if (click != null) {
        j(click).toggle();
    }
}


function saveTrackerFilter(filter_id) {
    // get all the tracker filter options    
    var filter_source_types = "";
    for (i=0;i<document.trackerFilterForm.filter_source_types.length;i++) {
        if (document.trackerFilterForm.filter_source_types[i].checked) {
            if (filter_source_types != "") {
                 filter_source_types += ",";
            }
            filter_source_types += document.trackerFilterForm.filter_source_types[i].value;
        }
    }

    var filter_watchlist_ids = "";
    for (i=0;i<document.trackerFilterForm.filter_watchlist_id.length;i++) {
        if (document.trackerFilterForm.filter_watchlist_id[i].checked) {
            if (filter_watchlist_ids != "") {
                 filter_watchlist_ids += ",";
            }
            filter_watchlist_ids += document.trackerFilterForm.filter_watchlist_id[i].value;
        }
    }

    var filter_insights_qtypes = "";
    for (i=0;i<document.trackerFilterForm.filter_insights_qtype.length;i++) {
        if (document.trackerFilterForm.filter_insights_qtype[i].checked) {
            if (filter_insights_qtypes != "") {
                 filter_insights_qtypes += ",";
            }
            filter_insights_qtypes += document.trackerFilterForm.filter_insights_qtype[i].value;
        }
    }
    
    var filter_name = document.trackerFilterForm.new_tracker_filter_name.value;
    if (filter_name == null || trim(filter_name) == "") {
        alert("The filter name cannot be blank.");
        return;
    }
    
    if (filter_name.length > 25) {
        alert("The filter name cannot exceed 25 characters.");
        return;
    }

    // do checks
    //alert("|" + filter_insights_qtypes + "|" + filter_watchlist_ids + "|" + filter_source_types + "|");
    if (filter_insights_qtypes == "" && (filter_watchlist_ids == "" || filter_source_types == "")) {
        alert("This filter will not return any tracked items. Select at least one watchlist and one news source type, or select at least one message option.");
        return;
    }

    if (filter_watchlist_ids == "" && filter_source_types != "") {
        alert("You have selected one or more news source types. Please also select at least one watchlist.");
        return;
    }
    
    if (filter_watchlist_ids != "" && filter_source_types == "") {
        alert("You have selected one or more watchlists. Please also select at least one news source type.");
        return;
    }

    var save_tracker_filter = getElem("save_tracker_filter");
    if (save_tracker_filter != null) {
        j(save_tracker_filter).hide();
    }
    var cancel_tracker_filter = getElem("cancel_tracker_filter");
    if (cancel_tracker_filter != null) {
        j(cancel_tracker_filter).hide();
    }
    var new_tracker_loading = getElem("new_tracker_loading");
    if (new_tracker_loading != null) {
        j(new_tracker_loading).show();
    }

    var params = {filter_id:filter_id, filter_name:filter_name, filter_source_types:filter_source_types, filter_watchlist_ids:filter_watchlist_ids, filter_insights_qtypes:filter_insights_qtypes};
    var url = "/tracker/save_tracker_filter";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
                alert("Oops. Unable to add filter.");
                if (new_tracker_loading != null) {
                    j(new_tracker_loading).hide();
                }
                if (save_tracker_filter != null) {
                    j(save_tracker_filter).show();
                }
                if (cancel_tracker_filter != null) {
                    j(cancel_tracker_filter).show();
                }
            },
        success:
            function(data){
                if (data != "-1") {
                    var results = data.split('<!--divider-->');
                    var theHTML = results[0];
                    var just_saved_filter_id = results[1];
                    // load the items
                    if (just_saved_filter_id != "None") {
                        window.location = "/my/tracker/?fid=" + just_saved_filter_id;
                       // filterTrackedItems(just_saved_filter_id, 'filter');
                    }                    
                } else {
                    alert("Oops. Unable to add filter.");
                    if (new_tracker_loading != null) {
                        j(new_tracker_loading).hide();
                    }
                    if (save_tracker_filter != null) {
                        j(save_tracker_filter).show();
                    }
                    if (cancel_tracker_filter != null) {
                        j(cancel_tracker_filter).show();
                    }
                }                
            }
   });
    
}


function deleteTrackerFilter(filter_id) {
    // get all the tracker filter options    
    var del = window.confirm("Are you sure you want to delete this filter?");
    if (!del) {
        return;   
    }
    
    var save_tracker_filter = getElem("save_tracker_filter");
    if (save_tracker_filter != null) {
        save_tracker_filter.disabled = true;
    }
    var cancel_tracker_filter = getElem("cancel_tracker_filter");
    if (cancel_tracker_filter != null) {
        cancel_tracker_filter.disabled = true;
    }
    var delete_tracker_filter = getElem("delete_tracker_filter");
    if (delete_tracker_filter != null) {
        j(delete_tracker_filter).hide();
    }
    var delete_tracker_loading = getElem("delete_tracker_loading");
    if (delete_tracker_loading != null) {
        j(delete_tracker_loading).show();
    }

    var params = {filter_id:filter_id};
    var url = "/tracker/delete_tracker_filter";
    j.ajax({
        type: "POST",
        url: url,
        data: params, 
        cache: false,
        error:
            function() {
                alert("Oops. Unable to delete filter.");
                j.closeDialog();
            },
        success:
            function(data){
                if (data != "-1") {
                    var results = data.split('<!--divider-->');
                    var theHTML = results[0];
                    var newly_selected_filter_id = results[1];
                    // load the items
                    if (newly_selected_filter_id != "None") {
                        window.location = "/my/tracker/?fid=" + newly_selected_filter_id;
                       // filterTrackedItems(just_saved_filter_id, 'filter');
                    }
                } else {
                    alert("Oops. Unable to delete filter.");
                    j.closeDialog();
                }                
            }
   });
    
}

function toggleMoreConnectionUpdates() {
    var more_connection_updates = getElem("more_connection_updates");
    if (more_connection_updates != null) {
        j(more_connection_updates).toggle();
    }

    var show_more_updates_link = getElem("show_more_updates_link");
    if (show_more_updates_link != null) {
        j(show_more_updates_link).toggle();
    }
}


document.onclick = hideUpdatesFilters;
document.onclick = closeAllPopups;
document.onmouseover = stopInactivityTimer;
document.onmouseout = startInactivityTimer;
//document.onkeypress = doShortCuts;

