var gIsLive = true;
var SearchEngineEnum = {
  Scour:   0,
  Google:  1,
  Yahoo:   2,
  MSN:     3,
  YouTube: 4,
  OneRiot: 5
};

var SortByEnum = {
  Scour:0,
  Google:1,
  Yahoo:2,
  MSN:3,
  OneRiot:4
};

var SearchType = {
  Web: 1,
  Image: 2,
  Video: 3,
  Comments: 4,
  Votes: 5,
  Community: 6,
  Local: 7
};

var userSettings = {
  disabledSearchTypes: true,
  disableSafeSearch: false,
  googleWeight: 100,
  numYahooResults: 10,
  numGoogleResults: 8,
  yahooWeight: 100,
  msnWeight: 100,
  oneriotWeight: 80,
  showSortingButtons: true,
  openLinksInVotingFrame: false,
  sortResultsBy: SortByEnum.Scour,
  username: '',
  userid: '',
  showflydown: true,
  showpostfirstsearchpopup: true,
  numMSNResults: 10,
  isSurveyVisited: false,
  showHomePageBox: true,
  introSearches: 0,
  showSearchInvitePsst: true,
  showWebAwardBox: true,
  showPageNumberHint: true,
  lastSearchTerm: '',
  lastSearchPage: 0,
  lastSearchType: SearchType.Web,
  showSerpsGiveawayBanner: true,
  showSerpsRealtimeNoticePsst: true,
  showSurveyHeaderRewards: true,
  lastLocation: '',
  checkBCT: true,

  isLoggedIn: function()
  {
    return this.username != '';
  },

  restoreDefaults: function()
  {
    this.disabledSearchTypes = true;
    this.disableSafeSearch = false;
    this.googleWeight = 100;
    this.numYahooResults = 10;
    this.yahooWeight = 100;
    this.msnWeight = 100;
    this.oneriotWeight = 80;
    this.showSortingButtons = true;
    this.openLinksInVotingFrame = false;
    this.numMSNResults = 10;
    this.numGoogleResults = 10;
    cookies.saveSettings();
  }
};
window.userSettings = userSettings;

function CookieManager() {}
CookieManager.prototype =
{
  getCookie: function(name, defaultValueP)
  {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return defaultValueP;
  },

  setCookie: function(name,value,days)
  {
    var expires;
    if (days) {
		  var date = new Date();
		  date.setTime(date.getTime()+(days*24*60*60*1000));
		  expires = "; expires="+date.toGMTString() + ";";
	  }
	  else expires = "";
    var cookie_value = name+"="+value+expires+"; path=/";

    if (gIsLive)
      cookie_value += ';domain=.scour.com';
    else
      cookie_value += ';domain=scour.webdev.thinkingbig.net';

	  document.cookie = cookie_value;
  },

  clearCookie: function(name)
  {
    this.setCookie(name, "");
  }
};

function AppCookies() {}

AppCookies.prototype =
{
  load: function()
  {
    this.loadSettings();
  },

  loadSettings: function()
  {
    cm = new CookieManager();
    var u = userSettings;
    u.disabledSearchTypes = cm.getCookie('disabledSearchTypes', 'true') == 'true';
    u.disableSafeSearch = cm.getCookie('disableSafeSearch', 'true') == 'true';
    u.googleWeight = Number(cm.getCookie('googleWeight', 100));
    u.numYahooResults = Number(cm.getCookie('numYahooResults', 10));
    u.yahooWeight = Number(cm.getCookie('yahooWeight', 100));
    u.msnWeight = Number(cm.getCookie('msnWeight', 100));
    u.oneriotWeight = Number(cm.getCookie('oneriotWeight', 80));
    u.showSortingButtons = cm.getCookie('showSortingButtons', 'true') == 'true';
    u.showSU = cm.getCookie('showSU', 'false') == 'true';
    u.sortResultsBy = cm.getCookie('sortResultsBy', SortByEnum.Scour);
    u.username = cm.getCookie('username', '');
    u.userid = cm.getCookie('userid', '');
    u.openLinksInVotingFrame = cm.getCookie('openLinksInVotingFrame', 'false') == 'true';
    u.showflydown = cm.getCookie('showflydown', 'true') == 'true';
    u.showpostfirstsearchpopup = cm.getCookie('showpostfirstsearchpopup', 'true') == 'true';
    u.numMSNResults = Number(cm.getCookie('numMSNResults', 10));
    u.isSurveyVisited = cm.getCookie('isSurveyVisited', 'false') == 'true';
    u.showHomePageBox = cm.getCookie('showHomePageBox', 'true') == 'true';
    u.introSearches = Number(cm.getCookie('introSearches', 0));
    u.showSearchInvitePsst = cm.getCookie('showSearchInvitePsst', 'true') == 'true';
    u.showWebAwardBox = cm.getCookie('showWebAwardBox', 'true') == 'true';
    u.numGoogleResults = cm.getCookie('numGoogleResults', 8);
    u.showPageNumberHint = cm.getCookie('showPageNumberHint', 'true') == 'true';
    u.lastSearchTerm = cm.getCookie('lastSearchTerm', '');
    u.lastSearchPage = Number(cm.getCookie('lastSearchPage', 0));
    u.lastSearchType = Number(cm.getCookie('lastSearchType', ''), SearchType.Web);
    u.showSerpsGiveawayBanner = cm.getCookie('showSerpsGiveawayBanner', 'true') == 'true';
    u.showSerpsRealtimeNoticePsst = cm.getCookie('showSerpsRealtimeNoticePsst', 'true') == 'true';
    u.showSurveyHeaderRewards = cm.getCookie('showSurveyHeaderRewards', 'true') == 'true';
    u.lastLocation = cm.getCookie('lastLocation', '');
    u.checkBCT = cm.getCookie('checkBCT', 'true') == 'true';
  },

  saveSettings: function()
  {
    cm = new CookieManager();
    var u = userSettings;
    var days = 365 * 10; // 10 years
    cm.setCookie('disabledSearchTypes', u.disabledSearchTypes, days);
    cm.setCookie('disableSafeSearch', u.disableSafeSearch, days);
    cm.setCookie('googleWeight', u.googleWeight, days);
    cm.setCookie('numYahooResults', u.numYahooResults, days);
    cm.setCookie('yahooWeight', u.yahooWeight, days);
    cm.setCookie('msnWeight', u.msnWeight, days);
    cm.setCookie('oneriotWeight', u.oneriotWeight, days);
    cm.setCookie('showSortingButtons', u.showSortingButtons, days);
    cm.setCookie('sortResultsBy', SortByEnum.Scour, days);
    cm.setCookie('showflydown', u.showflydown, days);
    cm.setCookie('openLinksInVotingFrame', u.openLinksInVotingFrame, days);
    cm.setCookie('showpostfirstsearchpopup', u.showpostfirstsearchpopup, days);
    cm.setCookie('numMSNResults', u.numMSNResults, days);
    cm.setCookie('isSurveyVisited', u.isSurveyVisited, days);
    cm.setCookie('showHomePageBox', u.showHomePageBox, days);
    cm.setCookie('introSearches', u.introSearches, days);
    cm.setCookie('showSearchInvitePsst', u.showSearchInvitePsst, days);
    cm.setCookie('showWebAwardBox', u.showWebAwardBox, days);
    cm.setCookie('numGoogleResults', u.numGoogleResults, days);
    cm.setCookie('showPageNumberHint', u.showPageNumberHint, days);
    cm.setCookie('lastSearchTerm', u.lastSearchTerm, days);
    cm.setCookie('lastSearchPage', u.lastSearchPage, days);
    cm.setCookie('lastSearchType', u.lastSearchType, days);
    cm.setCookie('showSerpsGiveawayBanner', u.showSerpsGiveawayBanner, days);
    cm.setCookie('showSerpsRealtimeNoticePsst', u.showSerpsRealtimeNoticePsst, days);
    cm.setCookie('showSurveyHeaderRewards', u.showSurveyHeaderRewards, days);
    cm.setCookie('lastLocation', u.lastLocation, days);
    cm.setCookie('checkBCT', u.checkBCT, 30);
  },

  setSearch: function(termP, pageIndexP, searchTypeP)
  {
    var u = window.userSettings;
    u.lastSearchTerm = termP;
    u.lastSearchPage = pageIndexP;
    u.lastSearchType = searchTypeP;

    this.saveSettings();
  },

  setSurveyVisisted:function()
  {
    userSettings.isSurveyVisited = true;

    this.saveSettings();
  },

  setShowedSearchPsst:function()
  {
    userSettings.isSurveyVisited = true;

    this.saveSettings();
  },

  setShowSurveyHeaderRewards: function()
  {
    userSettings.showSurveyHeaderRewards = false;

    this.saveSettings();
  }
};

window.cookies = new AppCookies();
window.cookies.load();

gSubID = 0;

(function($) {
  $.scour = $.scour || {};
  $.scour.consts =
  {
    domain: 'scour.com'
  };
  $.scour.util = {
    addSearchProvider: function()
    {
      if (window.external && ('AddSearchProvider' in window.external))
        window.external.AddSearchProvider('http://'+$.scour.consts.domain+'/searchplugins/scour.xml');
      else if (window.sidebar && ("addSearchEngine" in window.sidebar))
        window.sidebar.addSearchEngine ('http://'+$.scour.consts.domain+'/searchplugins/scour.src', 'http://'+$.scour.consts.domain+'/searchplugins/scour.gif', 'scour', 'The Social Search Engine');
      else
        alert("No search engine plugin support detected (FireFox or IE 7 required)");
      return false;
    }
  };
  $.scour.homepage =
  {
    escapeSearch: function(searchP)
    {
      searchP = searchP.replace(/\//g, ' ');
      var result = encodeURIComponent(searchP);

      result = result.replace(/'/gi, '%27');

      return result;
    },
    getActiveTab: function(postfixP)
    {
      if (postfixP == undefined) postfixP = '';
      if ($('#nSearch-container'+postfixP).hasClass("nSearch-w"))
        return 'web';
      else if ($('#nSearch-container'+postfixP).hasClass("nSearch-i"))
        return 'images';
      else if ($('#nSearch-container'+postfixP).hasClass("nSearch-v"))
        return 'video';
      else if ($('#nSearch-container'+postfixP).hasClass("nSearch-l"))
        return 'local';
      else if ($('#tabComments'+postfixP).hasClass("activetab"))
        return 'comment';
      else if ($('#tabVotes'+postfixP).hasClass("activetab"))
        return 'vote';
      else if ($('#tabCommunity'+postfixP).hasClass("activetab"))
        return 'community';
      else
        return 'web';
    },

    getSearchType: function(postfixP)
    {
      var search_type_text = this.getActiveTab(postfixP)
      switch(search_type_text)
      {
        case "web":
          return SearchType.Web;
        case "images":
          return SearchType.Image;
        case "video":
          return SearchType.Video;
        case "comment":
          return SearchType.Comments;
        case "vote":
          return SearchType.Votes;
        case "community":
          return SearchType.Community;
        case "local":
          return SearchType.Local;
        default:
          return SearchType.Web;
      }
    },

    getSearchTypeText: function(searchTypeP)
    {
      switch(searchTypeP)
      {
        case SearchType.Web:
          return "web";
        case SearchType.Image:
          return "images";
        case SearchType.Video:
          return "video";
        case SearchType.Local:
          return "local";
        case SearchType.Comments:
          return "comment";
        case SearchType.Votes:
          return "vote";
        case SearchType.Community:
          return "community";
      }
    },

    search: function(postfixP)
    {
      if (postfixP == undefined) postfixP = '';
      var txt = $('#txtSearch'+postfixP).get(0).value;
      var locale = $('#localSearchArea'+postfixP).get(0).value;

      window.cookies.setSearch(this.escapeSearch(txt), 0, this.getSearchType(postfixP));
      var url;
      var tab = this.getActiveTab(postfixP);
      if (tab == 'local')
      {
        userSettings.lastLocation = $('#localSearchArea').val();
        cookies.saveSettings();
      }
      if (tab == "vote")
        url = '/votes/search/all/'+this.escapeSearch(txt)+'/';
      else if (tab == "comment")
        url = '/comments/search/all/'+this.escapeSearch(txt)+'/';
      else if (tab == 'local')
        url = '/search/' + tab + '/' + this.escapeSearch(txt)+'/local/'+this.escapeSearch(locale)+'/';
      else
        url = '/search/' + tab + '/' + this.escapeSearch(txt);

      if (gSubID != undefined && gSubID == 1)
        url += '/abc/';
      if (txt != '')
        window.location.href = url;

      return false;
    },
    setActiveTab: function(tabID, postfixP)
    {
      if (postfixP == undefined) postfixP = '';
      if (tabID == "tabWeb"+postfixP) $('#tabWeb'+postfixP).addClass("activetab"); else $('#tabWeb'+postfixP).removeClass("activetab");
      if (tabID == "tabImages"+postfixP) $('#tabImages'+postfixP).addClass("activetab"); else $('#tabImages'+postfixP).removeClass("activetab");
      if (tabID == "tabVideo"+postfixP) $('#tabVideo'+postfixP).addClass("activetab"); else $('#tabVideo'+postfixP).removeClass("activetab");
      if (tabID == "tabComments"+postfixP) $('#tabComments'+postfixP).addClass("activetab"); else $('#tabComments'+postfixP).removeClass("activetab");
      if (tabID == "tabVotes"+postfixP) $('#tabVotes'+postfixP).addClass("activetab"); else $('#tabVotes'+postfixP).removeClass("activetab");
      if (tabID == "tabCommunity"+postfixP) $('#tabCommunity'+postfixP).addClass("activetab"); else $('#tabCommunity'+postfixP).removeClass("activetab");

      return false;
    }
  };
})(jQuery);;

var ScourHomepageTimer = null;
var ScourUpdateHomepageEveryInSeconds = 180;
var ScourCurrentGonnaUpdateHomepageIn = null;

$(document).ready(function(){
  var nSearchContainer = $('#nSearch-container')[0];
  $('#nSearch-tabs div').click(function(e){
    $('#nSearch-container')
      .removeClass('nSearch-w')
      .removeClass('nSearch-i')
      .removeClass('nSearch-v')
      .removeClass('nSearch-l')
      .addClass('nSearch'+this.id.match(/-./)[0]);

    if (this.id == 'nSearch-local')
    {
      return;
      if ($('#txtSearch').val() == '')
        $('#txtSearch').val('What')
      if ($('#localSearchArea').val() == '')
        $('#localSearchArea').val('Where')

      $('#localSearchArea').focus(function(){
        if ($(this).val() == 'Where')
          $(this).val('');
      }).blur(function(){
        if ($(this).val() == '')
          $(this).val('Where');
      });

      $('#txtSearch').focus(function(){
        if ($(this).val() == 'What')
          $(this).val('');
      });
    }
  });
});


var SpyTimeouts = new Array();

function clearSpyTimeouts()
{
	for(var timeout in SpyTimeouts){
		clearTimeout(SpyTimeouts[timeout]);
	}
}

(function () {

	$.fn.listSpy = function (limit, interval, itemsP, wrappingClassNameP, itemHeightP, indexP) {
		var limit = limit || 4;
    var interval = interval || 10000;
		var items = itemsP;
		var wrappingClassName = wrappingClassNameP;
		var lastUpdateTime = new Date().getTime();

    return this.each(function () {
      var $list = $(this),
          currentItem = limit,
          total = items.length,
          height = itemHeightP;

      $list.css({ height : height * (limit-1) });

      $list.find('> li').filter(':gt(' + (limit) + ')').remove();

      function spy(forceUpdateP) {
        if (!forceUpdateP && (new Date().getTime()) - lastUpdateTime < interval)
				{
					SpyTimeouts[indexP] = setTimeout(spy, interval, items, wrappingClassName, itemHeightP);
			    return;
		    }

				var $insert = $(items[currentItem]).css({
            height : 0,
            opacity : 0
        }).prependTo($list);

        $insert.animate({ height : height, opacity: 1 }, 1000, function(){ $(this).css('filter', '') });
 				$list.find(' li:last').animate({ height: 0, opacity: 0}, 1000, function(){ $(this).remove(); });

				// safety call
				$list.find('> li').filter(':gt(' + (limit) + ')').remove();

        if (++currentItem >= total)
            currentItem = 0;

				lastUpdateTime = new Date().getTime();
        SpyTimeouts[indexP] = setTimeout(spy, interval, items, wrappingClassName, itemHeightP);
      }

      spy(true);
    });
	};
})();

$(document).ready(function() {
	if ($.browser.msie && $.browser.version.substr(0,1) < 8)
	  return;
	$('.homepage-latest-comment-term, .homepage-latest-vote-term, .homepage-latest-vote-site, .homepage-latest-comment-site').live("mouseover", function(){
		$(this).find('span').show('fast');
	});
  $('.homepage-latest-comment-term, .homepage-latest-vote-term, .homepage-latest-vote-site, .homepage-latest-comment-site').live("mouseout", function(){
    $(this).find('span').hide('fast');
  });
});

var ScourHomepageUpdater = function()
{
  $.ajax({
     url: '/services/trendingTopics',
 	   data: {},
	   type: 'post',
	   cache: false,
	   dataType: 'json',
     success: function(topics)
		 {
		 	 $('#homepage-popular-right-now').empty();
		 	 var items = [];
			 for (var i = 0; i < topics.length; i++) {
			 	 var new_item = '<li><a href="/search/web/' + topics[i].title + '" target="_blank" title="' + topics[i].title + ' is hot right now - click to check it out">' + topics[i].title + '</a></li>';
				 if (i < 7)
					 $('#homepage-popular-right-now').append(new_item);
	   	   items.push(new_item);
	     }

       $('#homepage-popular-right-now').listSpy(7, 10000, items, "trending-topic-spy", 25, 0);
     }
   });

	// comments etc
  $.ajax({
	  url: '/services/getHomepageData/',
	  data: {},
	  type: 'post',
	  cache: false,
	  dataType: 'json',
	  success: function(result)
	  {
			$('#homepage-update-timer span').text('Updating');
			if (!result)
		    return;
		  var comments = result.comments;
		  var votes = result.votes;
			var stats = result.stats;

		  if (votes) {
		    var len = votes.length;

		    var vote;
				var display_url;
				var vote_list = [];
				$('#recent-votes-contents').empty();
		    for (var i = len-1; i >= 0; i--) {
		      vote = votes[i];

					display_url = vote.Url.replace('http://www.', '').replace('http://', '').substring(0, 30);
          if (display_url[display_url.length-1] == '/')
            display_url = display_url.substring(0, display_url.length-1);
					var query = vote.Query;
					if (query.length > 20)
					  query = query.substring(0, 20) + '...';
					var voted_up = vote.Value == 1;

				  var html = [];
		      html.push("<li class='homepage-latest-vote ");
					if (voted_up)
					  html.push('voted-up');
					else
					  html.push('voted-down');
					html.push("'>");
          if (vote.AvatarSmall != '')
            html.push("  <a href='http://scour.com/profile/user/", vote.Username, "' title=\"Visit ", vote.Username, "'s profile\"><img src='", vote.AvatarSmall, "' align='left' width='38' height='38' /></a>");
          else
            html.push("  <a href='http://scour.com/profile/user/", vote.Username, "' title=\"Visit ", vote.Username, "'s profile\"><img src='/images/resultsV4/avatar-not-set.png' align='left' width='38' height='38'/></a>");

					html.push("  <div class='topline'>");
					html.push("    <div class='homepage-latest-vote-term'><a href='http://scour.com/search/web/", addslashes(vote.Query), "' target='_blank' title='", vote.Username, " searched for ", addslashes(vote.Query), "'>", addslashes(query), "</a><span></span> </div>");
					//html.push("    <span class='homepage-latest-vote-when'>", vote.DateTime, "</span>");
          if (vote.Value == 1)
            html.push('<span class="result-pop-Good"><span></span></span>');
          else
            html.push('<span class="result-pop-Bad"><span></span></span>');
					html.push("  </div>");

					html.push("  <div class='innerbox'>");
		      html.push("   <div>");
		      html.push("    <div class='homepage-latest-vote-site'>&nbsp;<a href='", addslashes(vote.Url), "' title='", addslashes(vote.Url), "' target='_blank''>", addslashes(display_url), "</a><span></span></div>");
          html.push("    <div class='homepage-latest-vote-user'><a href='http://scour.com/profile/user/", vote.Username, "' title=\"Visit ", vote.Username, "'s profile\" target='_blank'>", vote.Username, "</a></div>");
		      html.push('    <div class="clear" style="height: 2px"></div>');
		      html.push("   </div>");
					html.push(" </div>");
		      html.push("</li>");

					var item = html.join('');
					if (i > len - 6)
					  $("#recent-votes-contents").prepend(item);

					vote_list.push(item);
		    }

				if (len > 6)
				  $('#recent-votes-contents').listSpy(6, 10000, vote_list, "votes-spy", 65, 1);
		  }
		  if (comments) {
		    var template = $('#recent-comment-template').get(0).innerHTML;
				var comment_list = [];
				$('#recent-comments-contents').empty();
				var len = comments.length;
		    for (var i = len-1; i >= 0; i--) {
					var html = [];
		      var comment = comments[i];
		      var a = template;
		      var comment_text = comment.Comment;
					var avatar = comment.AvatarSmall;
					var display_url = comment.Url.replace('http://www.', '').replace('http://', '').substring(0, 30);
					if (display_url[display_url.length-1] == '/')
					  display_url = display_url.substring(0, display_url.length-1);
					if (avatar == '')
					  avatar = '/images/resultsV4/avatar-not-set.png';
		      if (comment_text.length > 80)
		        comment_text = comment_text.substring(0, 80) + '...';
		      a = a.replace(/##user##/gi, comment.Username).replace(/##avatar##/gi, "src='"+avatar+"'").replace(/##query##/gi, addslashes(comment.Keyword.substring(0, 25))).replace(/##url##/gi, addslashes(comment.Url)).replace(/##when##/gi, comment.DateTimePosted).replace(/##short-url##/gi, addslashes(display_url)).replace(/##comment##/gi, addslashes(comment_text)).replace('##fullcomment##', addslashes(comment.Comment));
		      if (comment.Positive == 1) {
		        a = a.replace(/##value##/gi, 'Good');
		        a = a.replace(/##value-display##/gi, '');
		      }
		      else {
		        a = a.replace(/##value##/gi, 'Bad');
		        a = a.replace(/##value-display##/gi, '');
		      }
          var new_item = '<li class="homepage-latest-comment ';
          if (comment.Positive == 1)
            new_item += 'voted-up';
          else
            new_item += 'voted-down';
          new_item += '">' + a + '</li>'

					if (i > len - 5)
				    $("#recent-comments-contents").prepend(new_item);
					comment_list.push(new_item);
		    }
		    if (len > 5)
		      $('#recent-comments-contents').listSpy(5, 10000, comment_list, "comment-spy", 80, 2);
		  }

			if (stats)
			{
				//$('#scour-homepage-stats-people-searches-today span').text(stats.people_searched_today);
				$('#scour-homepage-stats-users-online span').text(stats.users_online);
				$('#scour-homepage-stats-comments-today span').text(stats.comments_today);
				$('#scour-homepage-stats-votes-today span').text(stats.votes_today);
			}

			ScourCurrentGonnaUpdateHomepageIn = ScourUpdateHomepageEveryInSeconds-1;
			$('#homepage-update-timer span').text(ScourCurrentGonnaUpdateHomepageIn-1);

			if (ScourHomepageTimer)
			  clearTimeout(ScourHomepageTimer);
	  }
	});
};

ScourHomepageTimer = setTimeout(function(){
  ScourHomepageUpdater();
}, ScourUpdateHomepageEveryInSeconds*1000);


$(document).ready(function(){
  $("#nSearch-button").click(function(e){
		e.preventDefault();
		$.scour.homepage.search();
	});
  $('#searchform').keypress(function(e){
		if (e.which == 13)
		  $.scour.homepage.search();
  });

	if (userSettings.showHomePageBox) {
    $("#homepage-latest").show();
		$("#homepage-latest-close").show();
	}
	else{
		$("#homepage-latest-open").show();
	}

  if (!userSettings.isLoggedIn()) {
  	$("#signupnow").fadeIn("slow");
		$("#homepage-join-scour").fadeIn();
  }

  // show slidedown
  if (userSettings.showflydown)
    $("#dropout").slideDown();

  if (userSettings.username != '')
  {
    $("#welcome_user_name").html(userSettings.username);
    $("#welcome_user").show();
    $("#points_logout").show();
  }
  else
  {
    $("#sign_in_user").show();
    $("#new_user").show();
  }


  if (userSettings.showHomePageBox) {
    ScourHomepageUpdater();
  }

  $("#homepage-latest-close").click(function(e){
    e.preventDefault();
		this.blur();
		window.userSettings.showHomePageBox = false;
		cookies.saveSettings();
    $("#homepage-latest").slideToggle('slow');
    clearTimeout(ScourHomepageTimer);
		clearSpyTimeouts();
    ScourCurrentGonnaUpdateHomepageIn = ScourUpdateHomepageEveryInSeconds;
    $("#homepage-latest-open").show();
    $("#homepage-latest-close").hide();
  });

	$('#homepage-latest-open').click(function(e){
		e.preventDefault();
		this.blur();
    window.userSettings.showHomePageBox = true;
    cookies.saveSettings();
		$("#homepage-latest").slideToggle('slow');
		$("#homepage-latest-close").show();
    $("#homepage-latest-open").hide();
		ScourHomepageUpdater();
	});

	$('#dropleft').click(function(e){
	  e.preventDefault();
	  closeDrop();
	  $.scour.util.addSearchProvider();
	});

	if ($.browser.msie || $.browser.mozilla)
	{
		$('#makeHomepage').show();
		$('#makeHomepage').click(function(e){
		  e.preventDefault();
		  if (pageTracker)
			  pageTracker._trackPageview('/tracking/setHomepageClicked');
		  if ($.browser.msie)
		  {
		    document.body.style.behavior='url(#default#homepage)';
		    document.body.setHomePage('http://scour.com');
		  }
		  else
		  {
		    $('#makeHomepageBox').toggle();
		  }
    });
	}

  $('#verifyEmailNow, #verifyaccount-header-link').click(function(e){
    e.preventDefault();
    $("#verifyemailmodal").modal({
        close: false,
        overlayId: 'report-overlay',
        containerId: 'report-container'
      });
  });
  $('#verifymodal-resendverification').click(function(e){
    e.preventDefault();
    $.ajax({
      url: '/services/resendverification',
      data: null,
      type: 'post',
      cache: false,
      dataType: 'json',
      complete: function (xhr) {
        $('#verifymodal-notificationsent').fadeIn();
      }
    });
  });
});

$(document).ready(function(){
  if (false && window.userSettings.checkBCT)
  {
    var s = document.createElement('script');
    s.src = '/js/bct-min.js';
    s.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(s);
  }
});


var pageTracker;
function gaSSDSLoad (acctP) {
  var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."),
      s;
	acct = acctP;
  s = document.createElement('script');
  s.src = gaJsHost + 'google-analytics.com/ga.js';
  s.type = 'text/javascript';
  s.onloadDone = false;
  function init () {
    pageTracker = _gat._getTracker(acctP);
    pageTracker._trackPageview();
  }
  s.onload = function () {
    s.onloadDone = true;
    init();
  };
  s.onreadystatechange = function() {
    if (('loaded' === s.readyState || 'complete' === s.readyState) && !s.onloadDone) {
      s.onloadDone = true;
      init();
    }
  };
  document.getElementsByTagName('head')[0].appendChild(s);
}

function closeDrop()
{
	userSettings.showflydown = false;
	cookies.saveSettings();
	$('#dropout').slideToggle();
}

function addslashes (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // +   improved by: Nate
    // +   improved by: Onno Marsman
    // +   input by: Denny Wardhana
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: addslashes("kevin's birthday");
    // *     returns 1: 'kevin\'s birthday'

    return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\u0000/g, "\\0");
}
