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
};

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,
  locationOverride: '',

  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 = "";
	  document.cookie = name+"="+value+expires+"; path=/";
  },

  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.locationOverride = cm.getCookie('locationOverride', '');

  },

  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('locationOverride', u.locationOverride, days);
  },

  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();

/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 9/11/2008
 * @author Ariel Flesler
 * @version 1.4
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(h){var m=h.scrollTo=function(b,c,g){h(window).scrollTo(b,c,g)};m.defaults={axis:'y',duration:1};m.window=function(b){return h(window).scrollable()};h.fn.scrollable=function(){return this.map(function(){var b=this.parentWindow||this.defaultView,c=this.nodeName=='#document'?b.frameElement||b:this,g=c.contentDocument||(c.contentWindow||c).document,i=c.setInterval;return c.nodeName=='IFRAME'||i&&h.browser.safari?g.body:i?g.documentElement:this})};h.fn.scrollTo=function(r,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};a=h.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=h(k),d=r,l,e={},p=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(d)){d=n(d);break}d=h(d,this);case'object':if(d.is||d.style)l=(d=h(d)).offset()}h.each(a.axis.split(''),function(b,c){var g=c=='x'?'Left':'Top',i=g.toLowerCase(),f='scroll'+g,s=k[f],t=c=='x'?'Width':'Height',v=t.toLowerCase();if(l){e[f]=l[i]+(p?0:s-o.offset()[i]);if(a.margin){e[f]-=parseInt(d.css('margin'+g))||0;e[f]-=parseInt(d.css('border'+g+'Width'))||0}e[f]+=a.offset[i]||0;if(a.over[i])e[f]+=d[v]()*a.over[i]}else e[f]=d[i];if(/^\d+$/.test(e[f]))e[f]=e[f]<=0?0:Math.min(e[f],u(t));if(!b&&a.queue){if(s!=e[f])q(a.onAfterFirst);delete e[f]}});q(a.onAfter);function q(b){o.animate(e,j,a.easing,b&&function(){b.call(this,r,a)})};function u(b){var c='scroll'+b,g=k.ownerDocument;return p?Math.max(g.documentElement[c],g.body[c]):k[c]}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);

/*
 * jQuery history plugin
 *
 * sample page: http://www.mikage.to/jquery/jquery_history.html
 *
 * Copyright (c) 2006-2009 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 */
 jQuery.extend({historyCurrentHash:undefined,historyCallback:undefined,historyIframeSrc:undefined,historyInit:function(callback,src){jQuery.historyCallback=callback;if(src)jQuery.historyIframeSrc=src;var current_hash=location.hash.replace(/\?.*$/,'');jQuery.historyCurrentHash=current_hash;if(jQuery.browser.msie){if(jQuery.historyCurrentHash==''){jQuery.historyCurrentHash='#';}
jQuery("body").prepend('<iframe id="jQuery_history" style="display: none;"'+
(jQuery.historyIframeSrc?' src="'+jQuery.historyIframeSrc+'"':'')
+'></iframe>');var ihistory=jQuery("#jQuery_history")[0];var iframe=ihistory.contentWindow.document;iframe.open();iframe.close();iframe.location.hash=current_hash;}
else if(jQuery.browser.safari){jQuery.historyBackStack=[];jQuery.historyBackStack.length=history.length;jQuery.historyForwardStack=[];jQuery.lastHistoryLength=history.length;jQuery.isFirst=true;}
if(current_hash)
jQuery.historyCallback(current_hash.replace(/^#/,''));setInterval(jQuery.historyCheck,100);},historyAddHistory:function(hash){jQuery.historyBackStack.push(hash);jQuery.historyForwardStack.length=0;this.isFirst=true;},historyCheck:function(){if(jQuery.browser.msie){var ihistory=jQuery("#jQuery_history")[0];var iframe=ihistory.contentDocument||ihistory.contentWindow.document;var current_hash=iframe.location.hash.replace(/\?.*$/,'');if(current_hash!=jQuery.historyCurrentHash){location.hash=current_hash;jQuery.historyCurrentHash=current_hash;jQuery.historyCallback(current_hash.replace(/^#/,''));}}else if(jQuery.browser.safari){if(jQuery.lastHistoryLength==history.length&&jQuery.historyBackStack.length>jQuery.lastHistoryLength){jQuery.historyBackStack.shift();}
if(!jQuery.dontCheck){var historyDelta=history.length-jQuery.historyBackStack.length;jQuery.lastHistoryLength=history.length;if(historyDelta){jQuery.isFirst=false;if(historyDelta<0){for(var i=0;i<Math.abs(historyDelta);i++)jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());}else{for(var i=0;i<historyDelta;i++)jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());}
var cachedHash=jQuery.historyBackStack[jQuery.historyBackStack.length-1];if(cachedHash!=undefined){jQuery.historyCurrentHash=location.hash.replace(/\?.*$/,'');jQuery.historyCallback(cachedHash);}}else if(jQuery.historyBackStack[jQuery.historyBackStack.length-1]==undefined&&!jQuery.isFirst){if(location.hash){var current_hash=location.hash;jQuery.historyCallback(location.hash.replace(/^#/,''));}else{var current_hash='';jQuery.historyCallback('');}
jQuery.isFirst=true;}}}else{var current_hash=location.hash.replace(/\?.*$/,'');if(current_hash!=jQuery.historyCurrentHash){jQuery.historyCurrentHash=current_hash;jQuery.historyCallback(current_hash.replace(/^#/,''));}}},historyLoad:function(hash){var newhash;hash=decodeURIComponent(hash.replace(/\?.*$/,''));if(jQuery.browser.safari){newhash=hash;}
else{newhash='#'+hash;location.hash=newhash;}
jQuery.historyCurrentHash=newhash;if(jQuery.browser.msie){var ihistory=jQuery("#jQuery_history")[0];var iframe=ihistory.contentWindow.document;iframe.open();iframe.close();iframe.location.hash=newhash;jQuery.lastHistoryLength=history.length;jQuery.historyCallback(hash);}
else if(jQuery.browser.safari){jQuery.dontCheck=true;this.historyAddHistory(hash);var fn=function(){jQuery.dontCheck=false;};window.setTimeout(fn,200);jQuery.historyCallback(hash);location.hash=newhash;}
else{jQuery.historyCallback(hash);}}});


(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 ($('#tabComments'+postfixP).hasClass("activetab"))
        return 'comment';
      else if ($('#tabVotes'+postfixP).hasClass("activetab"))
        return 'vote';
      else if ($('#tabCommunity'+postfixP).hasClass("activetab"))
        return 'community';
    },

    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;
        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.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;

      window.cookies.setSearch(this.escapeSearch(txt), 0, this.getSearchType(postfixP));
      var url;
      var tab = this.getActiveTab(postfixP);

      if (tab == "vote")
        url = '/votes/search/all/'+this.escapeSearch(txt)+'/';
      else if (tab == "comment")
        url = '/comments/search/all/'+this.escapeSearch(txt)+'/';
      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 = '';
	  $('#nSearch-container'+postfixP).removeClass("nSearch-w").removeClass("nSearch-i").removeClass("nSearch-v");
      if (tabID == "tabWeb"+postfixP) $('#nSearch-container'+postfixP).addClass("nSearch-w");
      if (tabID == "tabImages"+postfixP) $('#nSearch-container'+postfixP).addClass("nSearch-i");
      if (tabID == "tabVideo"+postfixP) $('#nSearch-container'+postfixP).addClass("nSearch-v");
      if (tabID == "tabComments"+postfixP) $('#tabComments'+postfixP).addClass("activetab");
      if (tabID == "tabVotes"+postfixP) $('#tabVotes'+postfixP).addClass("activetab");
      if (tabID == "tabCommunity"+postfixP) $('#tabCommunity'+postfixP).addClass("activetab");

      return false;
    }
  };
})(jQuery);;

function showHide(idP)
{
  $("#"+idP).slideToggle("slow");
}

function trackABCConversion()
{
  var head = document.getElementsByTagName("head")[0];
  var abc_conversion = document.createElement('script');
  abc_conversion.type = 'text/javascript';
  abc_conversion.src = 'http://67.29.139.253/cgi-bin/saletrack.pl?username=scourad&cachebuster=' + new Date().getTime().toString();
  head.appendChild(abc_conversion);
}

function doVoteFrame(index, url, title, domain)
{
  title = unescape(title);
  if (gIsCanuck)
    trackABCConversion();


  if (pageTracker)
    pageTracker._trackPageview('/outgoing/resultclick/'+searcher.searchType+'/'+searcher.search_query+'/'+gSource);

  $.ajax({
    url: '/services/resultClick/',
    data: {
      'query': searcher.search_query,
      'click_url' : url,
      'search_type' : searcher.searchType
    },
    type: 'post',
    cache: false,
    dataType: 'json',
    success: function ()
		{
      if (userSettings.openLinksInVotingFrame)
      {
        var encoded_url = Base64.encode(url);
        title = Base64.encode(encode(stripBolding(title.replace("/",''))));
        var query = encodeURIComponent(searcher.search_query).replace("/","");

        window.location.href = '/view/result/' + query + '/' + title + '/' + encoded_url + '/?URL=' + url;
      }
      else
      {
        window.location.href = url;
      }
    }
  });

  return true;
}

function searchOnDomain(domain)
{
  var qry = searcher.search_query;
  var site_search_index = qry.indexOf("site:");
  if (site_search_index >=0)
    qry = qry.substr(0, qry.indexOf("site:"));
  window.userSettings.lastSearchPage = 0;
  window.cookies.saveSettings();
  window.location.href = "/search/web/" + qry + " site:" + domain + '/related';
}

function resultClickThru(url)
{
  if (pageTracker)
    pageTracker._trackPageview('/outgoing/resultclick/'+searcher.searchType+'/'+searcher.search_query+'/'+gSource);
  $.ajax({
    url: '/services/resultClick/',
    data: {
      'query': searcher.search_query,
      'click_url' : url,
      'search_type' : searcher.searchType
    },
    type: 'post',
    cache: false,
    dataType: 'json',
    success: function () {    }
  });

  return true;
}

function clearComment(txtP)
{
  if (txtP && txtP.defaultValue==txtP.value)
  {
    txtP.value = "";
  }
}

function vote(index, button)
{
  if (!userSettings.isLoggedIn())
  {
    if (window.confirm("You must be logged in to vote.  Would you like to login now?"))
    {
      window.location.href = "/login/";
    }
    return false;
  }
  button.blur();
  button.onclick = dummy;

  $.ajax({
    url: '/services/addPosVote/',
    data: {
      'query': searcher.search_query,
      'url' : searcher.aggSearchResults.list[index].getFirstUrl()
    },
    type: 'post',
    cache: false,
    dataType: 'json',
    success: function () {
      getUserPoints();
    }
  });

  $('#voteup_link' + index).addClass('resultVoteUpComplete');
  $('#voteup_link' + index).attr({'title': "Voted Up. Thanks!"});
  $('#votedown_link'+index).fadeOut("slow");
  $('#votedown_link_frame'+index).fadeOut("slow");

  return false;
}

function votedown(index, button)
{
  if (!userSettings.isLoggedIn())
  {
    if (window.confirm("You must be logged in to vote.  Would you like to login now?"))
    {
      window.location.href = "/login/";
    }
    return false;
  }
  button.blur();
  button.onclick = dummy;

  //$('#vote_down' + index).removeClass('l_voteminus');
  $('#votedown_link' + index).addClass('resultVoteDownComplete');
  $('#votedown_link' + index).attr({'title': "Voted Down. Thanks!"});
  $('#voteup_link'+index).fadeOut("slow");
  $('#voteup_link_frame'+index).fadeOut("slow");

  $.ajax({
    url: '/services/addNegVote/',
    data: {
      'query': searcher.search_query,
      'url' : searcher.aggSearchResults.list[index].getFirstUrl()
    },
    type: 'post',
    cache: false,
    dataType: 'json',
    success: function () {
      getUserPoints();
    }
  });

  return false;
}

function commentvoteup(index, button)
{
  if (!userSettings.isLoggedIn())
  {
    if (window.confirm("You must be logged in to vote.  Would you like to login now?"))
    {
      window.location.href = "/login/";
    }
    return false;
  }
  button.blur();
  button.onclick = dummy;

  $.ajax({
    url: '/services/addPosVote/',
    data: {
      'query': searcher.search_query,
      'url' : searcher.aggSearchResults.list[index].getFirstUrl()
    },
    type: 'post',
    cache: false,
    dataType: 'json',
    success: function (data) {
      getUserPoints();
    }
  });

  $('#voteup_link' + index).addClass('resultVoteUpComplete');
  $('#voteup_link' + index).attr({'title': "Voted Up. Thanks!"});
  $('#votedown_link'+index).fadeOut("slow");
  $('#votedown_link_frame'+index).fadeOut("slow");

  return false;
}

function commentvotedown(index, button)
{
  if (!userSettings.isLoggedIn())
  {
    if (window.confirm("You must be logged in to vote.  Would you like to login now?"))
    {
      window.location.href = "/login/";
    }
    return false;
  }
  button.blur();
  button.onclick = dummy;

  //$('#vote_down' + index).removeClass('l_voteminus');
  $('#votedown_link' + index).addClass('resultVoteDownComplete');
  $('#votedown_link' + index).attr({'title': "Voted Down. Thanks!"});
  $('#voteup_link'+index).fadeOut("slow");
  $('#voteup_link_frame'+index).fadeOut("slow");

  $.ajax({
    url: '/services/addNegVote/',
    data: {
      'query': searcher.search_query,
      'url' : searcher.aggSearchResults.list[index].getFirstUrl()
    },
    type: 'post',
    cache: false,
    dataType: 'json',
    success: function (data) {
      getUserPoints()
    }
  });

  return false;
}

function dummy() {}

function showFeedbackForm(){
  document.getElementById('feedback-name').value = userSettings.username;
  document.getElementById('feedback-section').value = window.location.href;

  // create a modal dialog with the data
  $("#feedbackform").modal({
    close: false,
    overlayId: 'feedback-overlay',
    containerId: 'feedback-container',
    onOpen: feedback.open,
    onShow: feedback.show,
    onClose: feedback.close
  });
  return false;
};

function toogleVotingFrame()
{
  userSettings.openLinksInVotingFrame = !userSettings.openLinksInVotingFrame;
  cookies.saveSettings();
  var text = "on";
  if (!userSettings.openLinksInVotingFrame)
    text = "off";
  $("#toogleVotingFrameStatus").text(text);
}

function hideHomePageBox()
{
  userSettings.showHomePageBox = false;
  cookies.saveSettings();
  $("#homepage_explination").fadeOut("slow");
  $("#learnmore").fadeOut("slow");
  $("#homepageMoreInfo").fadeIn("slow");
}

function showHomepageBox()
{
  userSettings.showHomePageBox = true;
  cookies.saveSettings();
  $("#homepage_explination").fadeIn("slow");
  $("#learnmore").fadeIn("slow");
  $("#homepageMoreInfo").fadeOut("slow");
}

function closeComment(indexP)
{
  $("#l_comments" + indexP).slideToggle();
}

function getUserPoints()
{
	return;
  /*if (userSettings.userid > 0)
  {
    $.get('/services/getPoints/' + new Date().getTime() + '/', null,
      function(data)
    {
      var user_searches = Number(data.user_searches);       if (user_searches == NaN) user_searches=0;
      var user_votes = Number(data.user_votes);             if (user_votes == NaN) user_votes=0;
      var user_comments = Number(data.user_comments);       if (user_comments == NaN) user_comments=0;
      var user_bonus = Number(data.user_bonus);             if (user_bonus == NaN) user_bonus=0;
      var user_points = Number(data.user_points);           if (user_points == NaN) user_points=0;
      var friend_searches = Number(data.friend_searches);   if (friend_searches == NaN) friend_searches=0;
      var friend_votes = Number(data.friend_votes);         if (friend_votes == NaN) friend_votes=0;
      var friend_comments = Number(data.friend_comments);   if (friend_comments == NaN) friend_comments=0;
      var friend_points = Number(data.friend_points);       if (friend_points == NaN) friend_points=0;
      var new_messages = Number(data.new_msg_count);       if (new_messages == NaN) new_messages=0;
      $("#mypoints_usersearches").text(numberFormatWithCommas(user_searches));
      $("#mypoints_comments").text(numberFormatWithCommas(user_comments));
      $("#mypoints_votes").text(numberFormatWithCommas(user_votes));
      $("#mypoints_bonus").text(numberFormatWithCommas(user_bonus));
      $("#mypoints_total").text(numberFormatWithCommas(user_points));
      $("#mypoints_friend_searches").text(numberFormatWithCommas(friend_searches));
      $("#mypoints_friend_comments").text(numberFormatWithCommas(friend_comments));
      $("#mypoints_friend_votes").text(numberFormatWithCommas(friend_votes));
      $("#mypoints_friend_total").text(numberFormatWithCommas(friend_points));
      $("#mypoints_usertotal").text(numberFormatWithCommas(user_points));
      $("#mypoints_total").text(numberFormatWithCommas(friend_points+user_points));
      $("#mypoints_total_s").text(numberFormatWithCommas(friend_points+user_points));
      $("#mypoints_total").fadeIn("false");
      $("#mypoints_total_s").fadeIn("fast");

      if (!data.verified)
        $('#verifyaccount-header').fadeIn();

      if (new_messages > 0)
      {
        $('#header-new-message-count').html(new_messages);
        $('#header-new-messages').show();
      }
    }, "json");
  }*/
}

function addComment(comment, url, positive, txt, btn)
{
  if (userSettings.isLoggedIn())
  {
    var par = txt.parent().parent();
    $.ajax({
      url: '/services/addComment/',
      data: {
        'query': searcher.search_query,
        'comment': comment,
        'url': url,
        'positive': positive
      },
      type: 'post',
      cache: false,
      dataType: 'json',
      success: function (result) {
        if (result.success)
        {
          var avatar = result.avatar;
          txt.attr("disabled", "disabled");
          par.find('.addCommentPosted').text('Comment Posted, thanks!');
          par.find('.addCommentPosted').show();
          par.find('.addCommentErrors').hide();
          par.find('.addCommentPostNeg').hide();
          par.find('.addCommentPostPos').hide();

          //update the user's points
          getUserPoints();

          // add comment to current display
          var container = par.parent().find('.resultCommentsBox');
          var comment_result='';

          comment_result += '<div class="comMyComment" >';
          comment_result += '  <div class="comAvatarBar">';
          comment_result += '    <a href="/profile/user/'+(userSettings.username)+'" class="comAvatar">';
          if (avatar != '')
            comment_result += '      <img src="'+avatar+'" alt="" />';
//          else
//            result += '      <img src="/img/fakeavatarsmall.png" alt="" />';
          comment_result += '    </a>';
          comment_result += '    <div class="comBoxTip"></div>';
          comment_result += '  </div>';
          comment_result += '  <div class="comMain" id="justaddedcomment" style="display:none">';
          comment_result += '    <div class="comInfo">';
          comment_result += '      <a href="/profile/user/'+(userSettings.username)+'/" class="comUsername">'+userSettings.username.toString()+'</a>';
          comment_result += '      <span class="comTime">Just added</span>';
          comment_result += '      <div class="comReport" title="Report comment abuse"></div>';
          comment_result += '      <div class="comVoting">';
//          result += '        <div class="comVoteDown" title="Vote comment down"></div>';
//          result += '        <div class="comVoteUp" title="Vote comment up"></div>';
          comment_result += '        <div class="comPoints"> 0</div>';
          comment_result += '        <div class="comID" style="display:none">'+(result.commentid)+'</div>';
          comment_result += '      </div>';
          comment_result += '    </div>';
          comment_result += '    <div class="comBody">'+(comment)+'</div>';
          //result += '    <div class="comReply">reply</div>';
          comment_result += '  </div>';
          comment_result += '</div>';
          container.append(comment_result);
          $('#justaddedcomment').fadeIn('slow');
        }
        else
        {
          par.find('.addCommentErrors').text(result.error);
          par.find('.addCommentPosted').hide();
          par.find('.addCommentErrors').show();
          btn.show();
        }
      }
    });
  }
  else
  {
    if (window.confirm("You must be logged in to comment.  Would you like to login now?"))
    {
      showLoginModal();
    }
  }
}

function goodieView(gid, state) {
  if(state=="s") {
    document.getElementById(gid).style.display="block";
  } else {
    document.getElementById(gid).style.display="none";
  }
}

function recommendComment(id, positive, btn)
{
  $.ajax({
    url: '/services/recommendComment/',
    data: {
      'comment': id,
      'positive' : positive
    },
    type: 'post',
    cache: false,
    dataType: 'json',
    success: function (result)
    {
      $(btn).parent().find('.comPoints').text(result['num']);
    }
  });
}

function adClickThru(url, bid)
{
  if (pageTracker)
    pageTracker._trackPageview('/outgoing/adclick/'+searcher.searchType+'/'+searcher.search_query+'/'+gSource);

  if (gIsCanuck)
    trackABCConversion();


  $.ajax({
    url: '/services/addClickThru/',
    data: {
      'query': searcher.search_query,
      'url' : url,
      'search_type' : searcher.searchType,
      'bid': bid,
      'subid': gSubID
    },
    type: 'post',
    cache: false,
    dataType: 'json',
    complete: function () {
      window.location.href = url;
    }
  });
}


function addslashes( str ) {
  str=str.replace(/\\/g,'\\\\');
  str=str.replace(/\'/g,'\\\'');
  str=str.replace(/\"/g,'\\"');
  str=str.replace(/\0/g,'\\0');
  str=str.replace(/&#39;/g,'\\\'');

  return str;
}

function scourPointsClick()
{
  if (!userSettings.isLoggedIn())
  {
    window.location.href = "/login/";
  }
  else
  {
    window.location.href = "/profile/points/";
  }
}

function checkPaste(e){
  if($(this).val().length > searcher.addCommentTextboxValue.length+2) {
    e.stopPropagation();
    $(this).val(searcher.addCommentTextboxValue);
    var par = $(this).parent();
    par.find('.addCommentErrors').text('Sorry, no pasting, we want the details from you! :-)');
    par.find('.addCommentErrors').show();
    par.find('.addCommentPosted').hide();
  } else {
    searcher.addCommentTextboxValue = $(this).val();
  }
}

function boldTextSplit(haystackP, searchTermsP)
{
	var result = haystackP;
	var terms = searchTermsP.split(/\s/);
	for (var i = 0; i < terms.length; i++) {
	 if (terms[i] != '')
  	var regex = RegExp("(" + terms[i].replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1') + ")", "gi");
  	result = result.replace(regex, "<b>$1</b>");
  }
	return result;
}

function escapeRegExp(inputP) {
  if (inputP == undefined)
  {
	return '';
  }
  return
}

function stripBolding(inputP)
{
  if (inputP == undefined) return '';
  inputP = inputP.replace(/<strong>/gim, "");
  inputP = inputP.replace(/<\/strong>/gim, "");
  inputP = inputP.replace(/<b>/gim, "");
  inputP = inputP.replace(/<\/b>/gim, "");
  return inputP;
}

/*
 * SimpleModal 1.1.1 - jQuery Plugin
 * http://www.ericmmartin.com/projects/simplemodal/
 * http://plugins.jquery.com/project/SimpleModal
 * http://code.google.com/p/simplemodal/
 *
 * Copyright (c) 2007 Eric Martin - http://ericmmartin.com
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Revision: $Id: jquery.simplemodal.js 93 2008-01-15 16:14:20Z emartin24 $
 *
 */
(function($){$.modal=function(data,options){return $.modal.impl.init(data,options);};$.modal.close=function(){$.modal.impl.close(true);};$.fn.modal=function(options){return $.modal.impl.init(this,options);};$.modal.defaults={overlay:50,overlayId:'modalOverlay',overlayCss:{},containerId:'modalContainer',containerCss:{},close:true,closeTitle:'Close',closeClass:'modalClose',persist:false,onOpen:null,onShow:null,onClose:null};$.modal.impl={opts:null,dialog:{},init:function(data,options){if(this.dialog.data){return false;}this.opts=$.extend({},$.modal.defaults,options);if(typeof data=='object'){data=data instanceof jQuery?data:$(data);if(data.parent().parent().size()>0){this.dialog.parentNode=data.parent();if(!this.opts.persist){this.dialog.original=data.clone(true);}}}else if(typeof data=='string'||typeof data=='number'){data=$('<div>').html(data);}else{if(console){console.log('SimpleModal Error: Unsupported data type: '+typeof data);}return false;}this.dialog.data=data.addClass('modalData');data=null;this.create();this.open();if($.isFunction(this.opts.onShow)){this.opts.onShow.apply(this,[this.dialog]);}return this;},create:function(){this.dialog.overlay=$('<div>').attr('id',this.opts.overlayId).addClass('modalOverlay').css($.extend(this.opts.overlayCss,{opacity:this.opts.overlay/100,height:'100%',width:'100%',position:'fixed',left:0,top:0,zIndex:3000})).hide().appendTo('body');this.dialog.container=$('<div>').attr('id',this.opts.containerId).addClass('modalContainer').css($.extend(this.opts.containerCss,{position:'fixed',zIndex:3100})).append(this.opts.close?'<a class="modalCloseImg '+this.opts.closeClass
+'" title="'+this.opts.closeTitle+'"></a>':'').hide().appendTo('body');if($.browser.msie&&($.browser.version<7)){this.fixIE();}this.dialog.container.append(this.dialog.data.hide());},bindEvents:function(){var modal=this;$('.'+this.opts.closeClass).click(function(e){e.preventDefault();modal.close();});},unbindEvents:function(){$('.'+this.opts.closeClass).unbind('click');},fixIE:function(){var wHeight=$(document.body).height()+'px';var wWidth=$(document.body).width()+'px';this.dialog.overlay.css({position:'absolute',height:wHeight,width:wWidth});this.dialog.container.css({position:'absolute'});this.dialog.iframe=$('<iframe src="javascript:false;">').css($.extend(this.opts.iframeCss,{opacity:0,position:'absolute',height:wHeight,width:wWidth,zIndex:1000,width:'100%',top:0,left:0})).hide().appendTo('body');},open:function(){if(this.dialog.iframe){this.dialog.iframe.show();}if($.isFunction(this.opts.onOpen)){this.opts.onOpen.apply(this,[this.dialog]);}else{this.dialog.overlay.show();this.dialog.container.show();this.dialog.data.show();}this.bindEvents();},close:function(external){if(!this.dialog.data){return false;}if($.isFunction(this.opts.onClose)&&!external){this.opts.onClose.apply(this,[this.dialog]);}else{if(this.dialog.parentNode){if(this.opts.persist){this.dialog.data.hide().appendTo(this.dialog.parentNode);}else{this.dialog.data.remove();this.dialog.original.appendTo(this.dialog.parentNode);}}else{this.dialog.data.remove();}this.dialog.container.remove();this.dialog.overlay.remove();if(this.dialog.iframe){this.dialog.iframe.remove();}this.dialog={};}this.unbindEvents();}};})(jQuery);

var searcher = {
  rawSearchResults : new Collection(),
  aggSearchResults : new SResult(),
  sidebarHandler : null,
  votes : new VoteCollection(),
  _searchResultContainer : null,
  _pagerResultContainer : null,
  _searchingContainer : null,
  _timeResultContainer : null,
  _spellCheckContainer : null,
  finishedSearches : [],
  startTime: null,
  endTime: null,
  _finshedOPSIScores : [],
  search_query : "",
  searchType : "web",
  numPages : 0,
  currentPage : 0,
  _totalResultsAvailable : 0, // currently only used for image
  _requestedPage : 0,
  _spellCheckValue : "",
  _videoResults : new Collection(),
  haveGoogle: false,
  haveMSN: false,
  haveYahoo: false,
  haveOneRiot: false,
  haveScour: false,
  haveRendered: false,
  commentCounts: [],
  ads: [],
  addCommentTextboxValue: '',

  addResult: function(newResult)
  {
    this.rawSearchResults.add(newResult);
  },

  addVoteResult: function(newResult){
    this.votes.add(newResult);
  },

  calculateResults: function()
  {
    this.aggSearchResults.clear();

    var result;
    for(var index=0; index<this.rawSearchResults.count(); index++)
    {
      var item = this.rawSearchResults.list[index];
      result = this.aggSearchResults.getByUrl(item.link);

      var vote = this.votes.getByUrl(item.link);
      if (result != null)
      {
        result.add(item);

        if (vote != null)
        {
          result.addVote(vote);
        }
      }
      else
      {
        var new_result = new AggSResult(item);
        if (vote != null)
        {
          new_result.addVote(vote);
        }

        this.aggSearchResults.add(new_result);
      }
    }
    this.aggSearchResults.rankScores();
  },

  callbackSpellCheck: function(result)
  {
    this._spellCheckValue = result;
    var spellcheck = $("#spellcheck");
    if (result != "")
    {
      var div = $('#spellcheckterm');
      div.html('<a href="/search/' + this.searchType + "/" + result + '/related/" class="spellCheckLink">' + result + '</a>&nbsp;&nbsp;</span>');
      spellcheck.fadeIn('fast');
    }
    else
    {
      spellcheck.hide();
    }
  },

  callbackRelatedTerms: function(result)
  {
    var div = $('#spellcheckrelated');
    var len = result.length;
    var term, url;
    if (len > 5) len = 5;
    for(var i=0; i<len; i++)
    {
      term = result[i];
      url = "/search/" + this.searchType + "/" + encodeURIComponent(term) + "/related/";
      if (window.gSubID && window.gSubID == 1) url += "abc/";
      div.append("<a href='" + url + "'>" + boldTextSplit(term, this.search_query) + "</a>");
    }
    var related = $("#relatedterms");
    if (len > 0)
    {
      related.fadeIn('fast');
    }
    else
    {
      related.hide();
    }
  },

  callbackImageSearch: function()
  {
  },

  callbackEngineWebSearchComplete: function(engineTypeP)
  {
    this._finishedSearches.push(engineTypeP);

    if (!this.haveScour && !this.haveMSN && !this.haveYahoo && !this.haveGoogle)
      this.endTime = (new Date()).getTime();

    if (engineTypeP == SearchEngineEnum.Google)
      this.haveGoogle = true;
    if (engineTypeP == SearchEngineEnum.Yahoo)
      this.haveYahoo = true;
    if (engineTypeP == SearchEngineEnum.MSN)
      this.haveMSN = true;
    if (engineTypeP == SearchEngineEnum.Scour)
      this.haveScour = true;

    //if (!this.haveScour && this.haveMSN && this.haveYahoo && this.haveGoogle)
    if ((!this.haveRendered && engineTypeP != SearchEngineEnum.Scour && this.rawSearchResults > 0) || this._finishedSearches.length >= 5)
    {
      this.haveRendered = true;
      this.calculateResults();
      this.renderResults();
      this.setSearchTime();
      this.hideSearching();
      this.showSortByButtons();
      this.showBottomSearch();
    }
  },

  clearSearch : function()
  {
    this.aggSearchResults.clear();
    this._finishedSearches = [];
    this._finshedOPSIScores = [];
	if (this._searchResultContainer)
	  this._searchResultContainer.html("");

    this._pagerResultContainer.html("");
    this.rawSearchResults.clear();
    this.votes.clear();
    this.numPages = 0;
    this.clearSpellCheck();
    this._spellCheckValue = "";
    this._videoResults.clear();
  },

  clearSpellCheck: function()
  {
    $("#spellcheckterm").html('');
    $("#spellcheckrelated").html('');
  },

  createDelegate: function (instance, method) { return function () { return method.apply(instance, arguments); }; },

  displayCommentCounts: function()
  {
    if (this.haveRendered)
    {
      this.renderResults();
    }
  },

  doImageSearch: function(qry)
  {
    $('#searchingflickr').show('fast');
    $('#rightsidecell').hide('fast');
    //adUpdater.updateAds(qry);
    this._imageWrapper = new ImageSearchWrapper(this, searcher.createDelegate(this.callbackImageSearch));
    this._imageWrapper.setSearchPage(this._requestedPage);
    this._imageWrapper.search(qry, this._callback);
    spellCheckerWrapper.search(qry, this.createDelegate(this, this.callbackSpellCheck));
    relatedSearchWrapper.search(qry, this.createDelegate(this, this.callbackRelatedTerms));
    this.sidebarHandler.displayImageItems();
  },

  doWebSearch: function(qry)
  {
    this.showSearching();
    var search_query = qry;
    if (userSettings.disabledSearchTypes)
    {
      search_query += " -filetype:pdf -filetype:doc -filetype:ppt";
    }

    if (gIsAmerican)
      scourlocal.search(qry);

    oneriotWrapper.search(search_query, this, this.createDelegate(this, this.callbackEngineWebSearchComplete));

    if (userSettings.numGoogleResults>0)
      googleWrapper.search(search_query, this, this.createDelegate(this, this.callbackEngineWebSearchComplete));
    else
      this.callbackEngineWebSearchComplete(SearchEngineEnum.Google);

    if (userSettings.numYahooResults>0)
      yahooWrapper.websearch(search_query, this, this.createDelegate(this, this.callbackEngineWebSearchComplete));
    else
      this.callbackEngineWebSearchComplete(SearchEngineEnum.Yahoo);

    if (userSettings.numMSNResults>0)
    {
      bingWrapper.websearch(search_query, this, this.createDelegate(this, this.callbackEngineWebSearchComplete));
      //var a = new LiveSearchClass();
      //a.search(search_query, this);
    }
    else
      this.callbackEngineWebSearchComplete(SearchEngineEnum.MSN);

    this.doVoteCheck(qry, this, this.createDelegate(this, this.callbackEngineWebSearchComplete));

    adUpdater.updateAds(qry);
//    msnWrapper.search(search_query, this, this.createDelegate(this, this.callbackEngineWebSearchComplete));

    spellCheckerWrapper.search(qry, this.createDelegate(this, this.callbackSpellCheck));
    relatedSearchWrapper.search(qry, this.createDelegate(this, this.callbackRelatedTerms));
  },

  doVideoSearch: function(qry) {
    //adUpdater.updateAds(qry);
    youtubeVideoSearch(qry);
    spellCheckerWrapper.search(qry, this.createDelegate(this, this.callbackSpellCheck));
    relatedSearchWrapper.search(qry, this.createDelegate(this, this.callbackRelatedTerms));
    this.sidebarHandler.displayVideoItems();
  },

  doVoteCheck: function(qry, engine, callback)
  {
    $.ajax({
      url: '/services/getsearchdata/',
      data: {
        'query': qry
      },
      type: 'post',
      cache: false,
      dataType: 'json',
      complete: function(){
        callback(SearchEngineEnum.Scour);
      },
      success: function (data) {
        // handle votes
        var votes = data.votes;
        var len = votes.length;
        for(var i=0; i<len; i++)
        {
          engine.addVoteResult(new VoteResult(votes[i].Url, votes[i].NumVotes));
        }
        // handle comment counts
        engine.commentCounts = data.comments;
        engine.displayCommentCounts();
      }
    });
    setTimeout("handleVoteCheckTimeout()", 6000);
  },

  getFeaturedAdDisplayCode: function(ad)
  {
    var title = boldTextSplit(ad.title, this.search_query);
    var desc = boldTextSplit(ad.description, this.search_query).wordWrap(120, "<br />", 0);

    var html = '<div class="v2result" onclick="adClickThru(\'' + ad.redirect + '\', ' + ad.bid + '); return false;" style="cursor:pointer"><a href="'+ad.redirect+'" class="resultTitle">'+title+'</a>';
    html += '<a href="#" class="resultNewWindow" title="Open result in new window"></a>';
    html += '<div class="resultSponsored">Sponsored Link</div>';
    html += '<div class="resultMain">';
    html += '<div class="resultMainBorder">';
    html += ' <div class="resultContent">';
    html += '    <div class="resultSummary">'+desc+ '<div class="resultDomain">';
    html += '			  <a href="'+ad.redirect+'" class="resultDomainLink">'+ad.url+'</a>';
    html += '		  </div>';
    html += '    </div>';
    html += '	</div>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    return html;
  },

  getNoResultsDisplay: function()
  {
    var display = "<p style='font-size:120%' class='clear'>No results found containing your search.</p>";
    display += "<p style='font-size:110%'>Suggestions:<br />";
    display += "  <ul style='margin-left:10px'>";
    display += "    <li style='margin-left:20px;font-size:130%'>Make sure your spelling is correct.</li>";
    display += "    <li style='margin-left:20px;font-size:130%'>Try more general keywords.</li>";
    display += "    <li style='margin-left:20px;font-size:130%'>Try different keywords.</li>";
    display += "  </ul>";
    return display;
  },

  getSearchTime: function()
  {
    return (this.endTime - this.startTime) / 1000;
  },

  hideSearching : function()
  {
    $('#results').show();
    $('#pager').show();
    if (userSettings.showPageNumberHint)
      $('#pagerinfo').show();
    $('#searching').hide();
  },

  isSiteSearch: function()
  {
    if (!this.search_query) return false;
    else return this.search_query.indexOf('site:') != -1;
  },


  loadElements: function()
  {
    this._searchResultContainer = $('#results');
    this._pagerResultContainer = $('#pager');
    this._searchingContainer = $('#searching');
    this._timeResultContainer = $('#time');
    this._spellCheckContainer = $('#spellcheck');
  },

  renderResults : function()
  {
    var results = $('#results');
    results.empty();
    $('#pager').empty();
    if (this.aggSearchResults.count() == 0)
    {
      results.html(this.getNoResultsDisplay());
    }
    else
    {
      this.showPage(this.currentPage);
    }

    this.setupWebPager();
  },

  search: function(queryP)
  {
    this.clearSearch();
    this.search_query = queryP;
    this.startTime = (new Date()).getTime();
    this.sidebarHandler = new SidebarWrapper('image-sidebar');

    var u = window.userSettings;
    var search_type = $.scour.homepage.getSearchTypeText(u.lastSearchType);
    if ($.scour.homepage.escapeSearch(queryP) == u.lastSearchTerm && this.searchType == search_type)
    {
      this.currentPage = u.lastSearchPage;
      this._requestedPage = u.lastSearchPage;
    }
    else
    {
      // new search from not scour initiated search - reset page index
      u.lastSearchPage = 0;
    }

    if (this.searchType == "web")
      this.doWebSearch(queryP);
    else if (this.searchType == "images")
      this.doImageSearch(queryP);
    else if (this.searchType == "video")
      this.doVideoSearch(queryP);
    else
      this.doWebSearch(queryP);
  },

  setFontWeight: function(id, weight){
    var e  = $(id).get(0);
    if (e) e.style.fontWeight = weight;
  },

  setSearchTime : function()
  {
    var start;
    var end;
    if (this.searchType == "web")
    {
      start = Math.max((this.currentPage)*12, 0) + 1;
      end = Math.min(start + 11, this.aggSearchResults.count());
    }
    else
    {
      start = this._requestedPage * 50 + 1;
      end = start + 49;
    }

    $('#time').html("Page " + (this.currentPage+1) + " - Results " + (start) + "-" + end + " for " + this.search_query + "(" + this.getSearchTime() + " seconds)");
  },

  setSearchType: function(value)
  {
    if (value != 'images' && value != 'video')
    {
      this.searchType = 'web';
      $.scour.homepage.setActiveTab('tabWeb');
    }
    else
    {
      this.searchType = value;
      if (value == 'images')
        $.scour.homepage.setActiveTab('tabImages');
      else
        $.scour.homepage.setActiveTab('tabVideo');
    }
  },

  setTotalResultsAvailable: function(val)
  {
    alert('setTotalResultsAvailable needs to be written');
  },

  setupWebPager: function()
  {
    if (this.aggSearchResults.count() > 12)
    {
      this.numPages = Math.ceil(this.aggSearchResults.count()/12);
      var page = this.currentPage;
      var pager = "";
      if (page > 0)
      {
        //pager += '<a href="#'+(page).toString()+'" onclick="javascript:searcher.showPrevPage()" id="pagerPrev" title="Previous Page" class="havehistory">Prev</a>';
        pager += '<a href="#'+(page).toString()+'" id="pagerPrev" title="Previous Page" class="havehistory">Prev</a>';
      }
      else
      {
        pager += '<span id="pagerPrev" class="nextprev">Prev</span>';
      }
      for(var index=1; index<=this.numPages; index++)
      {
        if (index-1 == page)
          pager += '<span id="pagerPrev" class="nextprev">'+index+'</span>';
        else
          pager += '<a href="#'+index.toString()+'" title="View Page ' + index.toString() + '" class="havehistory">' + index.toString() + '</a>';
          //pager += '<a href="#'+index.toString()+'" onclick="javascript:searcher.showPage(' + (index-1).toString() + ')" title="View Page ' + index.toString() + '" class="havehistory">' + index.toString() + '</a>';
      }
      if (page+1 < this.numPages)
      {
        pager += '<a href="#'+(page+2).toString()+'" id="pagerNext" title="Next Page" class="havehistory">Next</a>';
        //pager += '<a href="#'+(page+1).toString()+'" onclick="javascript:searcher.showNextPage()" id="pagerNext" title="Next Page" class="havehistory">Next</a>';
      }
      else
      {
        pager += '<span id="pageNext" class="nextprev">Next</span>';
      }
      $('#pager').html(pager);
    }
  },

  showBottomSearch: function()
  {
    $('#bottomseearch').show();
  },

  showPage: function(pageIndex)
  {
    if (pageIndex < 0)
      pageIndex = 0;
    $('#results').empty();
    var display = "";
    this.currentPage = pageIndex;
    // save our page index
    window.userSettings.lastSearchPage = this.currentPage;
    window.cookies.saveSettings();
    this._searchResultContainer = $('#results').get(0);
    var container = $('#results');
    container.empty();
    var start = Math.max((pageIndex)*12, 0);
    var end = Math.min(start + 12, this.aggSearchResults.count());

    for(var index = start; index<end; index++)
    {
      var div = document.createElement("div");
      var a = this.aggSearchResults.list[index].getDisplayHTML(index);
      try { div.innerHTML = a;  }catch(e){}
      this._searchResultContainer.appendChild(div);
    }
    this.wireResults();
    this.setupWebPager();
    this.setSearchTime();
    this.updateAdditionalInfo();
    //this.engineOSPIScoreCompleted(AV.OSPIValueEnum.EngineScore);
  },

  showNextPage: function()
  {
    this.showPage(this.currentPage + 1);
  },

  showPrevPage: function()
  {
    this.showPage(this.currentPage - 1);
  },

  showSearching : function()
  {
    this._searchingContainer.show();
    this._searchResultContainer.hide();
    this._pagerResultContainer.hide();
  },

  showSortByButtons : function()
  {
    var e = $('#submenuTitle');
    if (userSettings.showSortingButtons)
    {
      e.show();
      var by = userSettings.sortResultsBy;
      if (by == SortByEnum.Scour) $('#sortByScour').addClass('sortByScour_selected'); else $('#sortByScour').removeClass('sortByScour_selected');
      if (by == SortByEnum.Google) $('#sortByGoogle').addClass('sortByGoogle_selected'); else $('#sortByGoogle').removeClass('sortByGoogle_selected');
      if (by == SortByEnum.Yahoo) $('#sortByYahoo').addClass('sortByYahoo_selected'); else $('#sortByYahoo').removeClass('sortByYahoo_selected');
      if (by == SortByEnum.MSN) $('#sortByLive').addClass('sortByLive_selected'); else $('#sortByLive').removeClass('sortByLive_selected');
    }
    else
      e.hide();
  },

  sortBy : function(by, forceRedisplayP)
  {
    if (by != userSettings.sortResultsBy || forceRedisplayP)
    {
      this.currentPage = 0;
      // save our page index
      window.userSettings.lastSearchPage = this.currentPage;
      window.cookies.saveSettings();
      this.aggSearchResults._sortyBy = by;
      userSettings.sortResultsBy = by;
      cookies.saveSettings();
      this.aggSearchResults.rankScores();
      this.renderResults();
      this.updateAdditionalInfo();
      this.showSortByButtons();
    }
  },

  updateAdditionalInfo: function()
  {
  },

  wireResults: function()
  {
$('#weighting-default').click(function(e){
  e.preventDefault();
  userSettings.googleWeight = 100;
  userSettings.yahooWeight = 100;
  userSettings.msnWeight = 100;
  userSettings.oneriotWeight = 60;
  cookies.saveSettings();
  window.location.reload();
});

$('#weighting-realtime').click(function(e){
  e.preventDefault();
  userSettings.googleWeight = 30;
  userSettings.yahooWeight = 30;
  userSettings.msnWeight = 30;
  userSettings.oneriotWeight = 100;
  cookies.saveSettings();
  window.location.reload();
});

    // show/hide new window icon
    $(".resultTitleRow").hover(
      function () {
        $(this).find(".resultNewWindow").show();
      },
      function () {
        $(this).find(".resultNewWindow").hide();
      }
    );

    $('.addCommentComment').focus(function()
    {
      var txt = $(this);
      if (txt.val() == "Be the first to Comment!")
        txt.val('');
    });

    // Add textarea event
    $('.addCommentComment').each(function(){
      watchTextarea($(this));
    });

    $('.addCommentComment').blur(function()
    {
      var comment_count = new Number($(this).parent().parent().find('.commentCount').text());
      var txt = $(this);
      if (txt.val() == '' && comment_count==0)
        txt.val('Be the first to Comment!');
    });

    // toggle comment display button
    $('.resultComments').click(function(){
      var par = $(this).parent();
      var parpar = par.parent();
      par.find('.resultCommentsArrow').toggleClass('arrowUp');
      parpar.children('.resultCommentsContainer').slideToggle();
      var ac = parpar.find('.addCommentPanel');
      ac.each(function(){
        $(this).find('.addCommentComment').width($(this).width()-250+"px");
      });

      var tx = ac.find('.addCommentComment');
      searcher.addCommentTextboxValue = tx.val();
      $(tx).keyup(checkPaste).keydown(checkPaste).click(checkPaste).blur(checkPaste).focus(checkPaste);

      var visible = par.find('.resultCommentsArrow').hasClass('arrowUp');


      if (visible)
      {
        var parparpar = parpar.parent();
        var comment_count = new Number(parparpar.find('.commentCount').text());
        parparpar.find('.comCurPage').text(0);
        var cur_page = 0;

        if (comment_count > 0)
        {
          var url = parparpar.find('.resultUrl').text();
          var container = parparpar.find('.resultCommentsBox');
          container.empty();
          // load comments
          $.ajax({
            url: '/services/getComments/',
            data: {
              'query': searcher.search_query,
              'url' : url,
              'page' : cur_page,
              'sort' : parparpar.find('.comCurPage').val()
            },
            type: 'post',
            cache: false,
            dataType: 'json',
            success: function (comments) {
            parparpar.find('.comCurPage').text(++cur_page);
             var len = comments.length;
             var result = '';
             for(var i=0; i<len; i++)
             {
               var c = comments[i];

               result += '<div class="';
               //comCommentSingle/comFriendComment/comMyComment
               if (c.id == userSettings.userid)
                 result += 'comMyComment';
               else if (c.positive == 1)
                 result += 'comCommentSinglePos';
               else if (c.positive == 0)
                 result += 'comCommentSingleNeg';
               else
                 result += 'comCommentSingle';

               result += '">';
               result += '  <div class="comAvatarBar">';
               result += '    <a href="/profile/user/'+c.username.toString()+'" class="comAvatar">';
               if (c.avatar != '')
                 result += '      <img src="'+c.avatar+'" alt="" />';
//               else
//                 result += '      <img src="/panel/img/fakeavatarsmall.png" alt="" />';
               result += '    </a>';
               result += '    <div class="comBoxTip"></div>';
               result += '  </div>';
               result += '  <div class="comMain" style="display:none">';
               result += '    <div class="comInfo">';
               result += '      <a href="/profile/user/'+(c.username.toString())+'/" class="comUsername">'+c.username.toString()+'</a>';
               result += '      <span class="comTime">'+ c.time.toString() +'</span>';
               result += '      <div class="comReport" title="Report comment abuse"></div>';
               result += '      <div class="comVoting">';
               result += '        <div class="comVoteDown" title="Vote comment down"></div>';
               result += '        <div class="comVoteUp" title="Vote comment up"></div>';
               result += '        <div class="comPoints"> '+(c.rec.toString())+'</div>';
               result += '        <div class="comID" style="display:none">'+(c.id.toString())+'</div>';
               result += '      </div>';
               result += '    </div>';
               result += '    <div class="comBody">'+(c.comment.toString())+'</div>';
               //result += '    <div class="comReply">reply</div>';
               result += '  </div>';
               result += '</div>';
              }
              container.append(result);
              container.find('.comMain').fadeIn('slow');

              var pager = container.parent().find('.commentLoadMore');
              if (comment_count > (cur_page)*10)
              {
                var start = (cur_page*10)+1;
                var end = (cur_page*10)+10;
                if (end > comment_count)
                  end = comment_count;
                pager.text('Load Comments ' + start + '-' + end + ' of ' + comment_count);
                pager.show();
                pager.css("visibility", "visible");
              }
              else
              {
                pager.css("visibility", "hidden");
              }

              // wire up comment controls
              container.find('.comVoteUp').bind("click.custom", function(){
                var id = $(this).parent().find('.comID').text();
                recommendComment(id, 1, this);
                $(this).unbind("click.custom");
                $(this).addClass('comVotedUp');
                $(this).parent().find('.comVoteDown').animate({'opacity':'0', 'width': '0px'});
              });

              container.find('.comVoteDown').bind("click.custom", function(){
                var id = $(this).parent().find('.comID').text();
                recommendComment(id, 0, this);
                $(this).unbind("click.custom");
                $(this).addClass('comVotedDown');
                $(this).parent().find('.comVoteUp').animate({'opacity':'0', 'width': '0px'});
              });

              container.find('.comReport').click(function(){
                var id = $(this).parent().find('.comID').text();
                var username = $(this).parent().parent().find('.comUsername').text();
                var comment = $(this).parent().parent().find('.comBody').text();

                $('#reportform-commentid').text(id);
                $('#report-form-author').val(username);
                $('#abusetype1').attr("checked", "checked");
                $('#report-form-comment').val(comment);

                $("#reportmodal").modal({
                    close: false,
                    overlayId: 'report-overlay',
                    containerId: 'report-container'
                  });
                $('#report-form-info').get(0).focus();
              });

              container.find('.comReply').click(function(){
                alert('We will wire this up when we have main comment functions down.\n  It will be a clone of that short of an indent for display.');
              });
            }
          });
        }
      }
    });

    $('.commentLowerClose').click(function(){
      var par = $(this).parent();
      var parpar = par.parent();
      par.find('.resultCommentsArrow').toggleClass('arrowUp');
      parpar.children('.resultCommentsContainer').slideToggle('slow', function(){
        $.scrollTo(parpar.parent().parent(), 450, {offset:-10});
      });
    });

    // add comment buttons
    $('.addCommentButton').click(function(){

      if (userSettings.isLoggedIn())
      {
        var ac = $(this).parent().find('.addCommentPanel');

        ac.show();

        // set textarea size;
        var tx = ac.find('.addCommentComment');
        tx.width(ac.width()-250+"px");
      }
      else
      {
        var gc = $(this).parent().find('.guestCommentPanel');
        gc.show();
        $.scrollTo(gc,450,{offset:-100});
      }
    });

    // login link to overlay
    $('.guestCommentLink').click(function(){
      showLoginModal();
    });

    $('.commentLoadMore').click(function(){
      var par = $(this).parent();
      var parpar = par.parent();
      var parparpar = parpar.parent();
      var comment_count = new Number(parparpar.find('.commentCount').text());
      var cur_page = new Number(parparpar.find('.comCurPage').text());

      if (comment_count > 0)
      {
        var url = parparpar.find('.resultUrl').text();
        var container = parparpar.find('.resultCommentsBox');
        //container.empty();
        // load comments
        $.ajax({
          url: '/services/getComments/',
          data: {
            'query': searcher.search_query,
            'url' : url,
            'page' : cur_page,
            'sort' : parparpar.find('.comSortSelect').val()
          },
          type: 'post',
          cache: false,
          dataType: 'json',
          success: function (comments) {
           parparpar.find('.comCurPage').text(++cur_page);
           var len = comments.length;
           for(var i=0; i<len; i++)
           {
             var c = comments[i];

             var result = '<div class="';
             //comCommentSingle/comFriendComment/comMyComment
             if (c.id == userSettings.userid)
               result += 'comMyComment';
             else if (c.positive == 1)
               result += 'comCommentSinglePos';
             else if (c.positive == 0)
               result += 'comCommentSingleNeg';
             else
               result += 'comCommentSingle';

             result += '">';
             result += '  <div class="comAvatarBar">';
             result += '    <a href="/profile/user/'+c.username.toString()+'" class="comAvatar">';
             if (c.avatar != '')
               result += '      <img src="'+c.avatar+'" alt="" />';
//             else
//               result += '      <img src="/panel/img/fakeavatarsmall.png" alt="" />';
             result += '    </a>';
             result += '    <div class="comBoxTip"></div>';
             result += '  </div>';
             result += '  <div class="comMain" style="display:none">';
             result += '    <div class="comInfo">';
             result += '      <a href="/user/'+c.username+'/" class="comUsername">'+c.username+'</a>';
             result += '      <span class="comTime">'+ c.time +'</span>';
             result += '      <div class="comReport"></div>';
             result += '      <div class="comVoting">';
             result += '        <div class="comVoteDown"></div>';
             result += '        <div class="comVoteUp"></div>';
             result += '        <div class="comPoints"> '+c.rec+'</div>';
             result += '        <div class="comID" style="display:none">'+c.id+'</div>';
             result += '      </div>';
             result += '    </div>';
             result += '    <div class="comBody">'+c.comment+'</div>';
             //result += '    <div class="comReply">reply</div>';
             result += '  </div>';
             result += '</div>';

             container.append(result);
            }
            container.find('.comMain').fadeIn('slow');

            var pager = container.parent().find('.commentLoadMore');
            if (comment_count > (cur_page)*10)
            {
              var start = (cur_page*10)+1;
              var end = (cur_page*10)+10;
              if (end > comment_count)
                end = comment_count;
              pager.text('Load Comments ' + start + '-' + end + ' of ' + comment_count);
              pager.show();
              pager.css("visibility", "visible");
            }
            else
            {
              pager.css("visibility", "hidden");
            }

            // wire up comment controls
            container.find('.comVoteUp').bind("click.custom", function(){
              var id = $(this).parent().find('.comID').text();
              recommendComment(id, 1, this);
              $(this).unbind("click.custom");
              $(this).addClass('comVotedUp');
              $(this).parent().find('.comVoteDown').animate({'opacity':'0', 'width': '0px'});
            });

            container.find('.comVoteDown').bind("click.custom", function(){
              var id = $(this).parent().find('.comID').text();
              recommendComment(id, 0, this);
              $(this).unbind("click.custom");
              $(this).addClass('comVotedUp');
              $(this).parent().find('.comVoteDown').animate({'opacity':'0', 'width': '0px'});
            });

            container.find('.comReport').click(function(){
              var id = $(this).parent().find('.comID').text();
              var username = $(this).parent().parent().find('.comUsername').text();
              var comment = $(this).parent().parent().find('.comBody').text();

              $('#reportform-commentid').text(id);
              $('#report-form-author').val(username);
              $('#abusetype1').attr("checked", "checked");
              $('#report-form-comment').val(comment);

              $("#reportmodal").modal({
                  close: false,
                  overlayId: 'report-overlay',
                  containerId: 'report-container'
                });
              $('#report-form-info').get(0).focus();
            });

            container.find('.comReply').click(function(){
              alert('We will wire this up when we have main comment functions down.\n  It will be a clone of that short of an indent for display.');
            });
          }
        });
      }

    });

    $('.comSortSelect').change(function(){
      var par = $(this).parent();
      var parpar = par.parent();
      par.find('.resultCommentsArrow').toggleClass('arrowUp');
      parpar.children('.resultCommentsContainer').slideToggle();
      var parparpar = parpar.parent();
      var comment_count = new Number(parparpar.find('.commentCount').text());
      parparpar.find('.comCurPage').text(0);
      var cur_page = 0;

      if (comment_count > 0)
      {
        var url = parparpar.find('.resultUrl').text();
        var container = parparpar.find('.resultCommentsBox');
        container.find('.comMain').fadeOut('slow');
        // load comments
        $.ajax({
          url: '/services/getComments/',
          data: {
            'query': searcher.search_query,
            'url' : url,
            'page' : 0,
            'sort' : $(this).val()
          },
          type: 'post',
          cache: false,
          dataType: 'json',
          success: function (comments) {
           container.empty();
           parparpar.find('.comCurPage').text(++cur_page);
           var len = comments.length;
           for(var i=0; i<len; i++)
           {
             var c = comments[i];

             var result = '<div class="';
             //comCommentSingle/comFriendComment/comMyComment
             if (c.id == userSettings.userid)
               result += 'comMyComment';
             else if (c.positive == 1)
               result += 'comCommentSinglePos';
             else if (c.positive == 0)
               result += 'comCommentSingleNeg';
             else
               result += 'comCommentSingle';


             result += '">';
             result += '  <div class="comAvatarBar">';
             result += '    <a href="/profile/user/'+c.username.toString()+'" class="comAvatar">';
             if (c.avatar != '')
               result += '      <img src="'+c.avatar+'" alt="" />';
//             else
//               result += '      <img src="/panel/img/fakeavatarsmall.png" alt="" />';
             result += '    </a>';
             result += '    <div class="comBoxTip"></div>';
             result += '  </div>';
             result += '  <div class="comMain" style="display:none">';
             result += '    <div class="comInfo">';
             result += '      <a href="/user/'+c.username+'/" class="comUsername">'+c.username+'</a>';
             result += '      <span class="comTime">'+ c.time +'</span>';
             result += '      <div class="comReport"></div>';
             result += '      <div class="comVoting">';
             result += '        <div class="comVoteDown"></div>';
             result += '        <div class="comVoteUp"></div>';
             result += '        <div class="comPoints"> '+c.rec+'</div>';
             result += '        <div class="comID" style="display:none">'+c.id+'</div>';
             result += '      </div>';
             result += '    </div>';
             result += '    <div class="comBody">'+c.comment+'</div>';
             //result += '    <div class="comReply">reply</div>';
             result += '  </div>';
             result += '</div>';

             container.append(result);
            }
            $('.comMain').fadeIn('slow');

            var pager = container.parent().find('.commentLoadMore');
            if (comment_count > (cur_page)*10)
            {
              var start = (cur_page*10)+1;
              var end = (cur_page*10)+10;
              if (end > comment_count)
                end = comment_count;
              pager.text('Load Comments ' + start + '-' + end + ' of ' + comment_count);
              pager.show();
              pager.css("visibility", "visible");
            }
            else
            {
              pager.css("visibility", "hidden");
            }

            // wire up comment controls
            container.find('.comVoteUp').bind("click.custom", function(){
              var id = $(this).parent().find('.comID').text();
              recommendComment(id, 1, this);
              $(this).unbind("click.custom");
              $(this).addClass('comVotedUp');
              $(this).parent().find('.comVoteDown').animate({'opacity':'0', 'width': '0px'});
            });

            container.find('.comVoteDown').bind("click.custom", function(){
              var id = $(this).parent().find('.comID').text();
              recommendComment(id, 0, this);
              $(this).unbind("click.custom");
              $(this).addClass('comVotedUp');
              $(this).parent().find('.comVoteDown').animate({'opacity':'0', 'width': '0px'});
            });

            container.find('.comReport').click(function(){
              var id = $(this).parent().find('.comID').text();
              var username = $(this).parent().parent().find('.comUsername').text();
              var comment = $(this).parent().parent().find('.comBody').text();

              $('#reportform-commentid').text(id);
              $('#report-form-author').val(username);
              $('#abusetype1').attr("checked", "checked");
              $('#report-form-comment').val(comment);

              $("#reportmodal").modal({
                  close: false,
                  overlayId: 'report-overlay',
                  containerId: 'report-container'
                });
              $('#report-form-info').get(0).focus();
            });

            container.find('.comReply').click(function(){
              alert('We will wire this up when we have main comment functions down.\n  It will be a clone of that short of an indent for display.');
            });
          }
        });
      }

    });
  }
};  /* end searcher*/

var adUpdater = {
  error: function() {},
  updateAds: function(qry)
  {
    if (window.gSubID == 11) return;

    $.ajax({
      url: '/services/getabcf/',
      data: {
        subid: gSubID,
        term: qry,
        is_uk: gIsUK,
        is_canuck: gIsCanuck
      },
      type: 'post',
      cache: false,
      dataType: 'json',
      success: function (ads) {
        var div = $('#featuredAds');
        div.empty();
        div.show();
        var len = ads.length;
        if (len > 0)
        {
          var ad_code;
          if (!gIsUK && !gIsCanuck)
          {
            for (var i=0; i<ads.length; i++)
            {
              ad_code = searcher.getFeaturedAdDisplayCode(ads[i]);
              $('#featuredAds').append(ad_code);
            }
          }else{
            // we want 3 on the top 2 on the bottom and remaining on the right
            var max_len = 3;
            if (len < max_len) max_len = len;
            for (var i=0; i<max_len; i++){
              ad_code = searcher.getFeaturedAdDisplayCode(ads[i]);
              $('#featuredAds').append(ad_code);
            }

            // only put bottom ones for uk
            if (len > 3 && !gIsCanuck){
              var current_start_index = max_len;
              max_len += 2;
              if (len < max_len) max_len = len;
              for (var i=3; i<max_len; i++){
                ad_code = searcher.getFeaturedAdDisplayCode(ads[i]);
                $('#adsbottom').append(ad_code);
              }
            }

            if (len > max_len) {
              var current_start_index = max_len;
              max_len += 8;

              if (len < max_len) max_len = len;
              $('#adsbar').append('<h2 class="sl f" style="font-size:90%">Sponsored Links</h2><div class="clear"></div>');
              for (var i=current_start_index; i<max_len; i++){
                var title = boldTextSplit(ads[i].title, searcher.search_query);
                var desc = boldTextSplit(ads[i].description, searcher.search_query);

                if (desc.length > 200)
                  desc = desc.substring(0, 200) + '...';
                var url = ads[i].url;
                if (url.length > 30)
                  url = url.substring(0, 30) + "...";

                $('#adsbar').append('<div class="adbarad" onclick="adClickThru(\'' + ads[i].redirect + '\', ' + ads[i].bid + '); return false;" style="cursor:pointer;display:none"><div class="clear"><a href="' + ads[i].redirect + '" onmouseover="return true">' + title + '</a></div><div class="clear">' + desc + '</div><span class="a">' + url + '</span><br></div><br />');
              }
              $('#adsbar').append('<div class="clear" style="padding-top:10px;padding-left:2px;"><a href="http://www.advertise.com/cgi-bin/referadvfree.pl?referrerId=scour" style="color:#0066FF;font-size:13px;font-weight:bolder" target="_blank">See your ad here...</a></div>');
              $('.adbarad').fadeIn('slow');
            }
          }
          $('#featuredAds').fadeIn('slow');
        }
      },
      error: adUpdater.error
    });

    if (!gIsUK)
    {
       return;
    }
  }
};

var msnWrapper = {
  search: function (qry, engine, callback)
  {
    $.getJSON("/search/getmsn/" + encodeURIComponent(qry) + "/" + userSettings.numMSNResults + '/' + (new Date()).getTime() + '/',
      function(data)
      {
        var weight = userSettings.msnWeight/100;
        var len = data.length;
        var r = data;
        var new_result;
        for(var i=0; i<len; i++)
        {
          new_result = new SearchResult(r[i].Url, r[i].Title, r[i].Description, SearchEngineEnum.MSN, i+1, r[i].DisplayUrl, r[i].CacheUrl, -1, "");
          new_result.score = (Math.pow(1.3,(10-i)) * weight);
          engine.addResult(new_result);
        }
        callback(SearchEngineEnum.MSN);
      }
    );
  }
};

function SearchResult(linkP, titleP, descP, engineP, rankP, displayUrlP, cacheUrlP, cacheSizeP, mimeTypeP, isDefaultP, realtimeAdditionaInfoP)
{
  this.link = linkP;
  this.title = titleP;
  this.desc = descP;
  this.engine = engineP;
  this.rank = rankP;
  this.displayUrl = displayUrlP;
  this.cacheUrl = cacheUrlP;
  this.cacheSize = cacheSizeP;
  this.mimeType = mimeTypeP;
  this.isDefault = isDefaultP;
  this.score = null;
	this.realtimeAdditionaInfo = realtimeAdditionaInfoP;

  this.bold = function(strP, searchP)
  {
    if (strP)
    {
      return strP.replace(new RegExp(escapeRegExp(searchP), "gi"), "<strong>" + searchP + "</strong>");
    }
    else
    {
      return "";
    }
  };

  this.displayHtml = function() {
    return '<p><a href="' + this.link + '">' + this.title + '</a><br /><div>' + this.desc + '</div><br />' + this.displayUrl + '</p>';
  };

  this.getDomain = function()
  {
    var url = this.normalizeURL();
    var index = url.indexOf("/");
    if (index == -1)
    {
      return url;
    }
    else
    {
      return url.substring(0, index);
    }
  };

  this.normalizeLink = function()
  {
    var linkP = this.link;

    if (linkP.startsWith("http://www."))
      return linkP.substring(11);
    else if (linkP.startsWith("https://www."))
      return linkP.substring(12);
    else if (linkP.startsWith("http://"))
      return linkP.substring(7);
    else if (linkP.startsWith("https://"))
      return linkP.substring(8);
    else if (linkP.startsWith("www"))
      return linkP.substring(3);
    else
      return linkP;
  };

  this.normalizeURL = function()
  {
    var url = this.displayUrl;
    var match = url.match(/^https?:\/\/(www\.)?(.*?)(\/?|\/(index|default)(\.\w*))$/i);
    return (match && match[2] ? match[2] : url).toLowerCase();
  };

  this.toString = function()
  {
    return this.normalizeLink();
  };
}

VoteResult = function(urlP, votesP)
{
  this.url = urlP;
  this.numVotes = votesP;
};

var spellCheckerWrapper = {
  buildSearchUri: function(query)
  {
    var api_key = this.getYahooApplicationID();

    var adult_ok = ''; // set to 1 for allow
    if (userSettings.disableSafeSearch) adult_ok = '1';
    return 'http://api.search.yahoo.com/WebSearchService/V1/spellingSuggestion?appid=' + api_key + '&output=json&query=' + encodeURIComponent(query) + '&callback=?&adult_ok=' + adult_ok;
  },

  getYahooApplicationID: function()
  {
    return 'rf4H64XV34F4l8UUfGVbsRCjyRzxcMxiJwNc4fnW01kBr3HxbkHE7UuYGIrq9V.otUPFZSM-';
  },

  search: function (qry, callback)
  {
    this.searchstarttime = (new Date()).getTime();

    $.getJSON(this.buildSearchUri(qry),
     function (data) {
        this._searchEndTime = (new Date()).getTime();
        if (data && data.ResultSet && data.ResultSet.Result)
        {
          callback(data.ResultSet.Result);
        }
      }
    );
  }
};

var relatedSearchWrapper = {
  buildSearchUri: function(query)
  {
    var api_key = this.getYahooApplicationID();

    var adult_ok = ''; // set to 1 for allow
    if (userSettings.disableSafeSearch) adult_ok = '1';
    return 'http://search.yahooapis.com/WebSearchService/V1/relatedSuggestion?appid=' + api_key + '&output=json&query=' + encodeURIComponent(query) + '&callback=?&adult_ok=' + adult_ok;
  },

  getYahooApplicationID: function()
  {
    return 'rf4H64XV34F4l8UUfGVbsRCjyRzxcMxiJwNc4fnW01kBr3HxbkHE7UuYGIrq9V.otUPFZSM-';
  },

  search: function (qry, callback)
  {
    this.searchstarttime = (new Date()).getTime();
    $.getJSON(this.buildSearchUri(qry),
     function (data) {
        if (data && data.ResultSet && data.ResultSet.Result)
        {
          callback(data.ResultSet.Result);
        }
      }
    );
  }
};

var gLocalSearchMap;

var scourlocal = {
  search : function(qry)
  {
    return;
    $.ajax({
        url: '/services/getlocal/',
        data: {
          'query': encodeURIComponent(searcher.search_query),
          'subid' : gSubID,
          'locationOverride': userSettings.locationOverride
        },
        type: 'post',
        cache: false,
        dataType: 'json',
        success: function (data) {
          if (data != undefined && data.length > 0)
          {
            $('#local-results').show();
            var show_map = GBrowserIsCompatible();
            if (show_map)
            {
              // build the map
              gLocalSearchMap = new GMap2(document.getElementById("local-results-map"));
              gLocalSearchMap.setCenter(new GLatLng(0,0),0);
              gLocalSearchMap.addControl(new GSmallMapControl());

              // add our records, build map locations and then display
              var bounds = new GLatLngBounds();
            }
            var icon = new GIcon(G_DEFAULT_ICON);
            var markerData = {};
            markerData.icon = icon;
            markerData.title = "";
            $('#local-results-title').append("<div>Your local search results for <b>"+qry+"</b> near <b>Sherman Oaks, Ca</b></div>");
            for(var i=0;i<data.length; i++)
            {
              var tagline = data[i].tagline;
              if (tagline == '')
                tagline = data[i].description;
              if (tagline.length > 40)
                tagline = tagline.substring(0, 40) + '...';
              var result = '<div><a href="'+ data[i].destination_url+'"><span class="local-result-name">' + data[i].name + '</span></a> - <span class="local-result-tagline">' + tagline + '</span><span class="local-search-rating_star-small-'+data[i].overall_rating+'"></span></a></div>';
              $('#local-results-list').append( result);

              if (show_map)
              {
                var point = new GLatLng(parseFloat(data[i].latitude), parseFloat(data[i].longitude));
                bounds.extend(point);
                var marker = new GMarker(point);
                markerData.title = data[i].name;
                gLocalSearchMap.addOverlay(marker);
              }
            }

            if (data.length > 8)
            {
              $('#local-results-list').append('<div><a href="http://losangeles.citysearch.com/listings/los-angeles-ca/test/56050?what='+qry+'" target="_blank" class="local-result-more">See More</a></div>');
            }

            if (show_map)
            {
              gLocalSearchMap.setZoom(gLocalSearchMap.getBoundsZoomLevel(bounds)-1);
              gLocalSearchMap.setCenter(bounds.getCenter(), 9);
            }
          }
        }
      });
  }
}

var oneriotWrapper = {
  callback: null,
  endTime: null,
  engine: null,
  searchStartTime:  null,
  webSearch: null,

  search : function(qry, engine, callback)
  {
    this.callback = callback;
    this.engine = engine;

    $.ajax({
        url: '/services/realtime/',
        data: {
          'query': encodeURIComponent(searcher.search_query),
          'num' : 10
        },
        type: 'post',
        cache: false,
        dataType: 'json',
        success: function (data) {
          if (parseInt(data.results.length) > 0)
          {
            var weight = userSettings.oneriotWeight / 100;
            var len = data.results[0].locations.length;
            for(var i=0; i<len; i++)
            {
              var r = data.results[0].locations[i];
              //redirectUri
              new_result = new SearchResult(r.uri, r.title, r.description, SearchEngineEnum.OneRiot, i+1, r.uri, '', -1, "", false, r.firstFound);
              new_result.score = (Math.pow(1.3,(10-i)) * weight);
              engine.addResult(new_result);
            }
          }
          this._searchEndTime = (new Date()).getTime();
          callback(SearchEngineEnum.OneRiot);
          searcher.haveOneRiot = true;
        }
      });

    setTimeout("handleOneRiotTimeout()", 6000);
  }
};


var googleWrapper = {
  callback: null,
  endTime: null,
  engine: null,
  searchStartTime:  null,
  webSearch: null,

  parseResult : function(dataP)
  {
    try
    {
      var weight = 1;
      weight = userSettings.googleWeight / 100;
      var r = dataP.responseData.results;
      var len = r.length;
      if (len > userSettings.numGoogleResults)
        len=userSettings.numGoogleResults;
      var new_result;
      for (var i = 0; i < len; i++)
      {
        new_result = new SearchResult(r[i].unescapedUrl, r[i].titleNoFormatting, r[i].content, SearchEngineEnum.Google, i+1, r[i].visibleUrl, r[i].cacheUrl, -1, "");
        new_result.score = (Math.pow(1.3,(10-i)) * weight);
        this.engine.addResult(new_result);
      }

      this.endTime = (new Date()).getTime();
    }
    catch (e)
    {
      alert("Failed to get google result with error: " + e.message);
    }
    searcher.havegoogle = true;
    if (this.callback)
    {
      this.callback(SearchEngineEnum.Google);
    }
  },

  search : function(qry, engine, callback)
  {
    this.callback = callback;
    this.engine = engine;

    $.getJSON('http://ajax.googleapis.com/ajax/services/search/web?q=' + encodeURIComponent(searcher.search_query) + '&v=1.0&start=1&rsz=large&lr=en&callback=?&', function(data){
        googleWrapper.parseResult(data);
        this._searchEndTime = (new Date()).getTime();
        callback(SearchEngineEnum.Google);
        searcher.haveGoogle = true;
      });

    setTimeout("handleGoogleTimeout()", 6000);
  }
};

var yahooWrapper = {
  searchstarttime: null,

  buildSearchUri: function(query)
  {
    var num_results = userSettings.numYahooResults;  // max 100
    var adult_ok = ''; // set to 1 for allow
    if (userSettings.disableSafeSearch)
      adult_ok = '-porn -hate';
    return 'http://boss.yahooapis.com/ysearch/web/v1/'+query+'?appid=58fa746f5973b117b63051c3b3d197be&filter='+adult_ok+'&count='+num_results+'&format=json&callback=?';
  },

  parseResult : function(resultP)
  {
    if (resultP && resultP.ysearchresponse && resultP.ysearchresponse.resultset_web)
    {
      var weight = 1;

      weight = userSettings.yahooWeight / 100;

      // get the result
      var results = resultP.ysearchresponse.resultset_web;
      var num = results.length;
      for(var index=0;index<num; index++)
      {
        var new_result = new SearchResult(results[index].url, results[index].title, results[index].abstract, SearchEngineEnum.Yahoo, index+1, results[index].dispurl);
        if (results[index].Cache)
        {
          new_result._cacheUrl = results[index].Cache.Url;
          new_result._cacheSize = results[index].Cache.Size;
        }

        new_result.score = (Math.pow(1.3,(10-index)) * weight);

        this.engine.addResult(new_result);
      }
    }
  },

  websearch: function (qry, engine, callback)
  {
    this.engine = engine;
    this.searchstarttime = (new Date()).getTime();

    $.getJSON(this.buildSearchUri(qry),
      function (data)
      {
        yahooWrapper.parseResult(data);
        this._searchEndTime = (new Date()).getTime();
        callback(SearchEngineEnum.Yahoo);
        searcher.haveYahoo = true;
      });
    setTimeout("handleYahooTimeout()", 6000);
  }
};

var bingWrapper = {
  searchstarttime: null,

  buildSearchUri: function(query)
  {
    var num_results = userSettings.numMSNResults;  // max 100
    var adult_ok = 'Off'; // set to 1 for allow
    if (userSettings.disableSafeSearch)
      adult_ok = 'Strict';
    return 'http://api.bing.net/json.aspx?appid=57B91027FB24A039463D7959B74A46DFA0BAC6D6&Query='+query+'&Sources=Web&Version=2.0&Market=en-us&Adult='+adult_ok+'&Options=&Web.Count='+num_results+'&Web.Offset=0&JsonType=callback&JsonCallback=?';
  },

  parseResult : function(resultP)
  {
    var errors = resultP.SearchResponse.Errors;
    if (errors != null)
      return;

    var results = resultP.SearchResponse.Web.Results;
    if (results == null)
      return;

    // resultP.SearchResponse.Web.Total
    var result = null;
    var weight = userSettings.yahooWeight / 100;
    for (var i=0; i<results.length; i++)
    {
      var new_result = new SearchResult(results[i].Url, results[i].Title, results[i].Description, SearchEngineEnum.MSN, i+1, results[i].DisplayUrl);
      if (results[i].CacheUrl)
      {
        new_result._cacheUrl = results[i].CacheUrl;
      }

      new_result.score = (Math.pow(1.3,(10-i)) * weight);

      this.engine.addResult(new_result);
    }
  },

  websearch: function (qry, engine, callback)
  {
    this.engine = engine;
    this.searchstarttime = (new Date()).getTime();

    $.getJSON(this.buildSearchUri(qry),
      function (data)
      {
        bingWrapper.parseResult(data);
        this._searchEndTime = (new Date()).getTime();
        callback(SearchEngineEnum.MSN);
        searcher.haveMSN = true;
      });
    setTimeout("handleMSNTimeout()", 6000);
  }
};


function SResult()
{
  this.list=[];

  this.add = function(value) { this.list[this.list.length] = value; };
  this.aggSearchResults = function() { };
  this.clear = function() {  this.list = [];  };
  this.count = function() { return this.list.length; };
  this.sort = function(sortMethodP)
  {
    var sortMethod = sortMethodP;
    if (sortMethodP == undefined)
    {
      sortMethodP = searcher.createDelegate(this, this.sortByNumber);
    }
    // update scores
    for(var i=0; i<this.list.length; i++)
      this.list[i].updateScore();

    this.list.sort(sortMethodP);
  };

  this.sortByNumber = function(a, b)
  {
    return a - b;
  };

  this.getByDomain = function(domainP)
  {
    for(var index = 0; index<this.count(); index++)
    {
      if (this.list[index].domain == domainP)
      {
        return this.list[index];
      }
    }
    return null;
  };
  this.getByUrl = function(urlP)
  {
    for(var index = 0; index<this.count(); index++)
    {
      if (this.list[index].getFirstUrl() == urlP)
      {
        return this.list[index];
      }
    }
    return null;
  };

  this.get_Score = function(indexP)
  {
    return this.list[indexP].score;
  },

  this.rankScores = function ()
  {
    var sort_by = userSettings.sortResultsBy;
    if (sort_by == SortByEnum.Scour)
      this.sort(this._sortCallbackScour);
    else if(sort_by == SortByEnum.Google)
      this.sort(this._sortCallbackGoogle);
    else if(sort_by == SortByEnum.Yahoo)
      this.sort(this._sortCallbackYahoo);
    else if(sort_by == SortByEnum.MSN)
      this.sort(this._sortCallbackMSN);
    else if(sort_by == SortByEnum.OneRiot)
      this.sort(this._sortCallbackOneRiot);
    else
      this.sort(this._sortCallbackScour);
  };

  this._sortCallbackScour = function(a, b)
  {
    return b._score - a._score;
  };

  this._sortCallbackGoogle= function(a, b)
  {
    return a.getGoogleRank() - b.getGoogleRank();
  };

  this._sortCallbackYahoo= function(a, b)
  {
    return a.getYahooRank() - b.getYahooRank();
  };

  this._sortCallbackMSN = function(a, b)
  {
    return a.getMSNRank() - b.getMSNRank();
  };

  this._sortCallbackOneRiot= function(a, b)
  {
    return a.getOneRiotRank() - b.getOneRiotRank();
  };
}

function Collection()
{
  this.list=[];
  this.add = function(newGuy) { this.list[this.list.length] = newGuy; };
  this.clear = function() { this.list=[]; };
  this.count = function() { return this.list.length; };
};

function VoteCollection()
{
  this.list=[];
  this.add = function(newGuy) { this.list[this.list.length] = newGuy; };
  this.clear = function() { this.list=[]; };
  this.count = function() { return this.list.length; };
  this.getByUrl = function(url)
  {
    for(var i=0; i<this.count(); i++)
    {
      if (this.list[i].url == url)
      {
        return this.list[i];
      }
    }
    return null;
  };
}

function AggSResult(searchResultP)
{
  this.list = [];
  this.votes = new VoteCollection();
  this.index = -1;
  this.domain = stripBolding(searchResultP.getDomain());
  this._score = -1;
  this._comments = null;

  this.add = function(value)
  {
    this.list[this.list.length] = value;
  };
  this.add(searchResultP);
  this.addVote = function(vote)
  {
    this.votes.add(vote);
  };
  this.count = function() { return this.list.length; };

  this.getResultByType = function(engineTypeP)
  {
    var num = this.count();
    for(var index = 0; index < num; index++)
    {
      if (this.list[index].engine == engineTypeP)
      {
        return this.list[index];
      }
    }
    return this.getDefaultResult();
  };

  this.getYahooResult = function()
  {
    return this.getResultByType(SearchEngineEnum.Yahoo);
  };

  this.getGoogleResult = function()
  {
    return this.getResultByType(SearchEngineEnum.Google);
  };

  this.getMSNResult = function()
  {
    return this.getResultByType(SearchEngineEnum.MSN);
  };

  this.getOneRiotResult = function()
  {
    return this.getResultByType(SearchEngineEnum.OneRiot);
  };

  this.getDefaultResult = function(typeP)
  {
    var r = new SearchResult('#', '', '', typeP, '-', '#', '', '-', '', true);
    r.score = 0;

    return r;
  };

  this.getDisplayLink = function(google, yahoo, msn, oneriot)
  {
    if (google.displayUrl != "#" && google.displayUrl)
      return google.displayUrl;
    else if (yahoo.displayUrl != "#" && yahoo.displayUrl)
      return yahoo.displayUrl;
    else if(msn.displayUrl != "#" && msn.displayUrl)
      return msn.displayUrl;
    else if (oneriot.displayUrl != "#" && oneriot.displayUrl)
      return oneriot.displayUrl;
    else
    {
      return "";
    }
  };

  this.getTitle = function(google, yahoo, msn, oneriot)
  {
    if (google.title.trim() != "")
      return google.title;
    else if (yahoo.title != "")
      return yahoo.title;
    else if(msn.title != "")
      return msn.title;
    else if(oneriot.title != "")
      return oneriot.title;
    else
    {
      return "";
    }
  };

  this.getUrl = function(google, yahoo, msn, oneriot)
  {
    if (google.link != "#" && google.link)
      return google.link;
    else if (yahoo.link != "#" && yahoo.link)
      return yahoo.link;
    else if(msn.link != "#" && msn.link)
      return msn.link;
    else if(oneriot.link != "#" && oneriot.link)
      return oneriot.link;
    else
      return "";
  };

  this.getGoogleRank = function()
  {
    var r = this.getGoogleResult().rank;
    if (isNaN(r)) r = 1000;
    return r;
  };

  this.getYahooRank = function()
  {
    var r = this.getYahooResult().rank;
    if (isNaN(r)) r = 1000;
    return r;
  };

  this.getMSNRank = function()
  {
    var r = this.getMSNResult().rank;
    if (isNaN(r)) r = 1000;
    return r;
  };

  this.getOneRiotRank = function()
  {
    var r = this.getOneRiotResult().rank;
    if (isNaN(r)) r = 1000;
    return r;
  };

  this.getSummary = function(google, yahoo, msn, oneriot)
  {
    if (google.desc != "")
      return google.desc;
    else if (yahoo.desc != "")
      return yahoo.desc;
    else if(msn.desc != "")
      return msn.desc;
    else if(oneriot.desc != "")
      return oneriot.desc;
    else
      return "";
  };

  this.getFirstUrl = function()
  {
    var google_result = this.getGoogleResult();
    var yahoo_result = this.getYahooResult();
    var msn_result = this.getMSNResult();
    var one_riot = this.getOneRiotResult();

    return this.getUrl(google_result, yahoo_result, msn_result, one_riot);
  };

  this.getDisplayHTML = function(indexP)
  {
    this.index = indexP;
    var google_result = this.getGoogleResult();
    var have_google = google_result.toString() != "#" &&  google_result.toString() != "";
    var yahoo_result = this.getYahooResult();
    var have_yahoo = yahoo_result.toString() != "#" && yahoo_result.toString() != "";
    var msn_result = this.getMSNResult();
    var have_msn = msn_result.toString() != "#" && msn_result.toString() != "";
    var oneriot_result = this.getOneRiotResult();
    var have_oneriot = oneriot_result.toString() != "#" && oneriot_result.toString() != "";
    var title = this.getTitle(google_result, yahoo_result, msn_result, oneriot_result);
    var org_title = title;
    var url = this.getUrl(google_result, yahoo_result, msn_result, oneriot_result);
    var summary = this.getSummary(google_result, yahoo_result, msn_result, oneriot_result);
    var display_link = this.getDisplayLink(google_result, yahoo_result, msn_result, oneriot_result);
    var domain = this.domain;

    // remove strong/b
    title = stripBolding(title);

    // shorten them
    summary = stripBolding(summary);
    // remove brs as we're gonna add our own
    summary.replace(/<br>/gi, '').replace(/<br \/>/gi, '');
    summary = summary.wordWrap(100, "<br />", 0);

    if (title.length > 80)
      title = title.substring(0, 60) + "...";

    display_link = url;
    if (display_link.length > 60)
      display_link = display_link.substring(0, 60) + "...";

    // bold keywords
    title = boldTextSplit(title, searcher.search_query);
    summary = boldTextSplit(summary, searcher.search_query);

    display_link = boldTextSplit(display_link, searcher.search_query);

    var comment_count = '';
    if (searcher.commentCounts[url] != undefined)
      comment_count = searcher.commentCounts[url];

    var link_url = url;
    if (userSettings.openLinksInVotingFrame)
    {
      var encoded_url = Base64.encode(url);
      var encoded_title = Base64.encode(stripBolding(title.replace(/\?/gi, '').replace(/\//gi, '')));
      var encoded_query = encodeURIComponent(searcher.search_query.replace(/\?/gi, '').replace(/\//gi, ''));
      link_url = '/view/result/' + encoded_query + '/' + encoded_title + '/' + encoded_url + '/?URL=' + url;
    }

    var search_query = searcher.search_query;
    search_query = addslashes(search_query);

    var result = [];

    result.push('<div class="v2result clear" id="result',indexP,'">');
    result.push('  <div class="resultTitleRow">');
    result.push('    <a href="',link_url,'" class="resultTitle" onclick="return doVoteFrame(' , indexP , ',\'' , url , '\', \'',escape(title.replace("?",'')) , '\',\'' , addslashes(domain) , '\');">');
    if (have_oneriot)
		{
			var source_info = oneriot_result.realtimeAdditionaInfo;
		  if (source_info != undefined)
			{
				//twitter
				if (source_info.userService == "TWITTER")
				{
					result.push('<span href="http://twitter.com/', source_info.userId,'" title="Realtime Twitter result via OneRiot from tweet: ',source_info.comment,'"><img src="http://assets.scour.com/images/resultsV3/twitter-icon.png" alt="Realtime Twitter result via OneRiot" />&nbsp;</span>');
				}
				else  // digg
				{
					result.push('<span href="http://digg.com/users/', source_info.userId,'" title="Realtime Digg result via OneRiot"><img src="http://assets.scour.com/images/resultsV3/digg-icon.png" alt="Realtime Twitter result via OneRiot" />&nbsp;</span>');
				}
	    }
			else
			  result.push('<img src="/images/resultsV3/realtime.png" alt="Realtime result" /> ');
	  }
    result.push(title);
    result.push('</a>');
    result.push('    <a href="',link_url,'" class="resultNewWindow" title="Open result in new window" target="_blank" onmouseup="resultClickThru(\'' , url , '\')"></a>');
    result.push('  </div>');
    result.push('  <div class="resultMain">');
    result.push('    <div class="resultRank" title="">');
    var search_encoded = encodeURIComponent(searcher.search_query);
		if (have_google)
      result.push('      <a href="http://www.google.com/search?q=' , search_encoded , '" title="This represents the search listing rank on Google #',google_result.rank,' - Click to search Google for ',search_query,'" target="_blank" class="resultGoogleRank"><span></span>',google_result.rank,'</a>');
    else
      result.push('      <a href="http://www.google.ca/search?q=' , search_encoded , '" title="This represents the search listing rank on Google(Not In Top Results) - Click to search Google for ',search_query,'" target="_blank" class="resultGoogleRankNone"><span></span>-</a>');
    if (window.gIsAussie)
      if (have_yahoo)
        result.push('      <a href="http://au.search.yahoo.com/search?p=' , search_encoded , '" title="This represents the search listing rank on Yahoo #',yahoo_result.rank,' - Click to search Yahoo for ',search_query,'" target="_blank" class="resultYahooauRank"><span></span> ',yahoo_result.rank,'</a>');
      else
        result.push('      <a href="http://au.search.yahoo.com/search?p=' , search_encoded , '" title="This represents the search listing rank on Yahoo(Not In Top Results) - Click to search Yahoo for ',search_query,'" target="_blank" class="resultYahooauRankNone"><span></span>-</a>');
    else if (window.gIsUK)
      if (have_yahoo)
        result.push('      <a href="http://uk.search.yahoo.com/search?p=' , search_encoded , '" title="This represents the search listing rank on Yahoo #',yahoo_result.rank,' - Click to search Yahoo for ',search_query,'" target="_blank" class="resultYahooauRank"><span></span> ',yahoo_result.rank,'</a>');
      else
        result.push('      <a href="http://uk.search.yahoo.com/search?p=' , search_encoded , '" title="This represents the search listing rank on Yahoo(Not In Top Results) - Click to search Yahoo for ',search_query,'" target="_blank" class="resultYahooauRankNone"><span></span>-</a>');
    else
      if (have_yahoo)
        result.push('      <a href="http://search.yahoo.com/search?p=' , search_encoded , '" title="This represents the search listing rank on Yahoo #',yahoo_result.rank,' - Click to search Yahoo for ',search_query,'" target="_blank" class="resultYahooRank"><span></span>' , yahoo_result.rank ,'</a>');
      else
        result.push('      <a href="http://search.yahoo.com/search?p=' , search_encoded , '" title="This represents the search listing rank on Yahoo(Not In Top Results) - Click to search Yahoo for ',search_query,'" target="_blank" class="resultYahooRankNone"><span></span>-</a>');
    if (have_msn)
      result.push('      <a href="http://search.msn.com/results.aspx?q=' , search_encoded ,'" title="This represents the search listing rank on MSN #',yahoo_result.rank,' - Click to search MSN for ',search_query,'" target="_blank" class="resultLiveRank"><span></span>' , msn_result.rank , '</a>');
    else
      result.push('      <a href="http://search.msn.com/results.aspx?q=' , search_encoded ,'" title="This represents the search listing rank on MSN(Not In Top Results) - Click to search MSN for ',search_query,'" target="_blank" class="resultLiveRankNone"><span></span>-</a>');
    if (have_oneriot)
      result.push('      <a href="http://www.oneriot.com/search?q=' , search_encoded ,'&st=web&ot=" title="This represents the search listing rank on OneRiot #',oneriot_result.rank,' - Click to search OneRiot for ',search_query,'" target="_blank" class="resultOneRiotRank"><span></span>' , oneriot_result.rank , '</a>');
    else
      result.push('      <a href="http://www.oneriot.com/search?q=' , search_encoded ,'&st=web&ot=" title="This represents the search listing rank on OneRiot(Not In Top Results) - Click to search OneRiot for ',search_query,'" target="_blank" class="resultOneRiotRankNone"><span></span>-</a>');

    result.push('    </div>');
    result.push('    <div class="resultMainBorder">');
    result.push('      <div class="resultContent">');
    result.push('        <div class="resultSummary">',summary,'</div>');
    result.push('        <div class="resultDomain">');
    result.push('          <a href="',url,'" class="resultDomainLink" onclick="return doVoteFrame(' , indexP , ',\'' , url , '\', \'' , escape(title.replace("?",'')) , '\',\'' , domain , '\');">',display_link,'</a>');
    result.push('          <a href="#" class="resultDomainSearch" onclick="return searchOnDomain(\'' , domain , '\');">Search this Site</a>');
    result.push('        </div>');
    result.push('        <a href="#" class="resultVoteUp" onclick="vote(' , indexP , ', this); return false;" id="voteup_link' , indexP , '"></a>');
    result.push('        <a href="#" class="resultVoteDown" onclick="votedown(' , indexP , ', this); return false;" id="votedown_link' , indexP , '"></a>');
    result.push('        <div class="resultComments">');
    result.push('          <span></span> ' , comment_count.toString() ,' comments');
    result.push('          <div class="resultCommentsArrow"></div>');
    result.push('        </div>');
    result.push('      </div>');
    result.push('      <div class="resultCommentsContainer" style="display:none;">');
    if (comment_count != '')
      result.push('        <div class="addCommentButton" onclick="$(\'#addComment',indexP,',#commentClose',indexP,'\').fadeIn(\'slow\');">Add Comment</div>');
    result.push('          <div class="commentLowerCloseTop" id="commentClose',indexP,'" style="display:none" onclick="$(\'#addComment',indexP,',#commentClose',indexP,'\').fadeOut(\'slow\');">Discard</div>');
    result.push('        <div class="comSort">');
    result.push('          <select class="comSortSelect">');
    result.push('            <option value="newest">Newest</option>');
    result.push('            <option value="oldest">Oldest</option>');
    result.push('            <option value="positive">Positive</option>');
    result.push('            <option value="negative">Negative</option>');
    result.push('            <option value="recommended">Recommended</option>');
    result.push('          </select>');
    result.push('        </div>');


    result.push('        <h2 class="resultCommentsTitle">');
    if (comment_count != '')
      result.push(comment_count , ' Comments');
    else
      result.push('&nbsp;');
    result.push('</h2>');
    result.push('        <div class="addCommentPanel" style="display:none" id="addComment',indexP ,'">');
    result.push('          <textarea id="addCommentComment" class="addCommentComment" rows="4" cols="50" oncontextmenu="return false;">');
    if (userSettings.isLoggedIn() && (comment_count == '' || comment_count == 0))
      result.push('Be the first to Comment!');
    result.push('</textarea>');
    result.push('          <a href="#" class="addCommentPostNeg"></a>');
    result.push('          <a href="#" class="addCommentPostPos"></a>');
    result.push('          <div class="addCommentErrors" style="display:none">');
    result.push('            <div class="addCommentErrorsIcon"></div>');
    result.push('            <span class="addCommentErrorsText"></span>');
    result.push('          </div>');
    result.push('          <div class="addCommentPosted" style="display:none">');
    result.push('            <span class="addCommentPostedText">Comment Posted, thanks!</span>');
    result.push('          </div>');
    result.push('          <div class="addCommentCharacters">');
    result.push('            <span class="currentCharacters">0</span>/500 characters');
    result.push('          </div>');
    result.push('        </div>');

    result.push('<div class="resultCommentsBox">');
    if (!userSettings.isLoggedIn())
    {
      result.push('        <div class="noCommentsHeader">Be the first to Comment!');
      result.push('&nbsp;&nbsp;<a href="#" class="guestCommentLink">Login</a> or <a href="/signup/" target="_blank">Join Now</a>!');
      result.push('        </div>');
    }
    result.push('</div>');
    result.push('<div class="commentLowerClose">Close</div>');

/*    result.push('        <div class="addCommentButton" '
    if (comment_count == '' || comment_count == 0)
      result.push('style="display:none"');

    result.push('>Add Comment</div>');*/
    result.push('        <div class="commentLoadMore" style="visibility: hidden"></div>');
    result.push('        <div class="addCommentPanel"');
    if (!userSettings.isLoggedIn())
      result.push(' style="display:none"');
    result.push('         >');
    result.push('          <textarea id="addCommentComment" class="addCommentComment" rows="4" cols="50" oncontextmenu="return false;">');
    if (userSettings.isLoggedIn() && (comment_count == '' || comment_count == 0))
      result.push('Be the first to Comment!');
    result.push('</textarea>');
    result.push('          <a href="#" class="addCommentPostNeg"></a>');
    result.push('          <a href="#" class="addCommentPostPos"></a>');
    result.push('          <div class="addCommentErrors" style="display:none">');
    result.push('            <div class="addCommentErrorsIcon"></div>');
    result.push('            <span class="addCommentErrorsText"></span>');
    result.push('          </div>');
    result.push('          <div class="addCommentPosted" style="display:none">');
    result.push('            <span class="addCommentPostedText">Comment Posted, thanks!</span>');
    result.push('          </div>');
    result.push('          <div class="addCommentCharacters">');
    result.push('            <span class="currentCharacters">0</span>/500 characters');
    result.push('          </div>');
    result.push('        </div>');
    if (!userSettings.isLoggedIn())
    {
      result.push('        <div class="guestCommentPanel" style="display:none">');
      result.push('           Please <a href="#" class="guestCommentLink">Login</a> to Comment.<br>');
      result.push('           If you don\'t have an account, <a href="/signup/" target="_blank">sign up now</a>!');
      result.push('        </div>');
    }
    result.push('        <span class="commentCount" style="display:none">' , comment_count.toString() , '</span>');
    result.push('        <span class="comCurPage" style="display:none">0</span>');
    result.push('        <span class="resultUrl" style="display:none">' , url , '</span>');
    result.push('        <span class="currentlyDisplayedCommentCount" style="display:none">0</div>');
    result.push('      </div>');
    result.push('    </div>');
    result.push('  </div>');
    result.push('</div>');
    return result.join('');
  };

  this.updateScore = function()
  {
    var score = 0;
    var i;
    for(i=0; i<this.list.length; i++)
      score += this.list[i].score;

    for(i=0; i<this.votes.list.length; i++)
      score += (this.votes.list[i].numVotes)/50;

    this._score = score;
  };
}
Array.prototype.contains = function(value)
{
  for(var index=0; index<this.length; index++)
  {
    if (this[index] == value) return true;
  }
  return false;
};

String.prototype.startsWith = function(s) { return this.indexOf(s)==0; };

String.prototype.trim = function()
{
  var s = this;
  while (s.substring(0,1) == ' ')
  {
    s = s.substring(1, s.length);
  }
  while (s.substring(s.length-1, s.length) == ' ')
  {
    s = s.substring(0,s.length-1);
  }
  return s;
};

String.prototype.wordWrap = function(m, b, c){
    var i, j, l, s, r;
    if(m < 1)
        return this;
    for(i = -1, l = (r = this.split("\n")).length; ++i < l; r[i] += s)
        for(s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : ""))
            j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length
            || c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
    return r.join("\n");
};


SidebarWrapper = function(targetIDP)
{
  this.targetID = targetIDP;
};

SidebarWrapper.prototype = {
  displayImageItems: function()
  {
    //$('#widget-sidebar').empty();
    this.displayNews();
    this.displayVideos();
    this.displayYAnswers();
    this.displayWeb();
  },

  displayVideoItems: function()
  {
    $('#widget-sidebar').empty();
    this.displayNews();
    this.displayYAnswers();
    this.displayWeb();
  },

  displayNews: function(){
    $.getJSON('http://ajax.googleapis.com/ajax/services/search/news?q=' + searcher.search_query + '&v=1.0&start=1&rsz=small&lr=en&callback=?&', function(data){
      var div = $('#widget-sidebar');
      var len = data.responseData.results.length;
      if (len > 3) len = 3;
      var news = '<div class="clear"><h3><span>News</span></h3>';

      if (len > 0)
      {
        for(var i=0;i<len; i++)
        {
          var result = data.responseData.results[i];
          var display_date = new Date(result.publishedDate);
          display_date = display_date.getFullYear().toString() + '/' + display_date.getMonth().toString() + '/' + display_date.getDay().toString();
          news += '<div class="serps-sidebaritem"><a href="'+result.unescapedUrl+'" target="_blank">'+result.titleNoFormatting+'</a><div class="serps-sidebar-source">Source: '+result.publisher+'</div><div class="serps-sidebar-date">'+display_date+'</div></div>';
        }
      }
      else{
        news += '<div class="serps-sidebar-duration padded" style="padding-top:0;margin-top:0;">No news found.</div>';
      }

      news += '</div>';

      div.append(news);
    });
  },

  displayVideos: function(){
    $.getJSON('http://ajax.googleapis.com/ajax/services/search/video?q=' + searcher.search_query + '&v=1.0&start=1&rsz=large&lr=en&callback=?&', function(data){
      var div = $('#widget-sidebar');
      if (data.responseData == null) return;
      var len = data.responseData.results.length;
      if (len > 5) len = 5;
      var content = '<div class="clear"><h3><span>Videos</span></h3>';

      if (len > 0)
      {
        for(var i=0;i<len; i++)
        {
          var result = data.responseData.results[i];
          content += '<div class="serps-sidebaritem clear"><a href="'+result.url+'" target="_blank"><img src="'+result.tbUrl+'" alt="" width="80" align="left" style="padding-right: 4px;" /></a><a href="'+result.url+'" target="_blank">'+result.titleNoFormatting+'</a><div class="serps-sidebar-duration">'+result.duration+' seconds</div></div>';
        }
      }
      else{
        content += '<div class="serps-sidebar-duration padded" style="padding-top:0;margin-top:0;">No videos found.</div>';
      }
      content += '</div>';

      div.append(content);
    });
  },

  displayYAnswers: function(){
    $.getJSON('http://answers.yahooapis.com/AnswersService/V1/questionSearch?query=' + searcher.search_query + '&appid=58fa746f5973b117b63051c3b3d197be&results=5&sort=date_desc&output=json&callback=?&', function(data){
      var div = $('#widget-sidebar');
      var len = data.all.count;
      if (len > 5) len = 5;
      if (len == 0) return;
      var content = '<div class="clear"><h3><span>Answers</span></h3>';

      if (len > 0)
      {
        for(var i=0;i<len; i++)
        {
          var result = data.all.questions[i];
          content += '<div class="serps-sidebaritem clear"><a href="'+result.Link+'" target="_blank">'+result.Subject+'</a><div class="serps-sidebar-duration">'+result.NumAnswers+' answers</div></div>';
        }
      }
      else{
        content += '<div class="serps-sidebar-duration padded" style="padding-top:0;margin-top:0;">No answers found.</div>';;
      }
      content += '</div>';

      div.append(content);
    });
  },

  displayWeb: function(){
    $.getJSON('http://ajax.googleapis.com/ajax/services/search/web?q=' + searcher.search_query + '&v=1.0&start=1&rsz=large&lr=en&callback=?&', function(data){
      var div = $('#image-news-sidebar');
      if (data.responseData == null) return;
      var len = data.responseData.results.length;
      if (len > 5) len = 5;
      var content = '<div class="clear"><h3><span>Web</span></h3>';

      if (len > 0)
      {
        for(var i=0;i<len; i++)
        {
          var result = data.responseData.results[i];
          content += '<div class="serps-sidebaritem clear"><a href="'+result.unescapedUrl+'" target="_blank">'+result.titleNoFormatting+'</a><div class="serps-sidebar-duration">'+result.content+'</div></div>';
        }
      }
      else{
        content += '<div class="serps-sidebar-duration padded" style="padding-top:0;margin-top:0;">No results found.</div>';
      }
      content += '</div>';

      div.append(content);
    });
  }
};

ImageSearchWrapper = function(engineP, onCompleteCallbackP)
{
  this._searchPage = 1;
  this.numResults = 0;
};
ImageSearchWrapper.prototype =
{
  returned_count: 0,
  have_results: false,
  completedCallback : function(data)
  {
    this.parseFlickrResult(data);
  },

  buildSearchUri: function(query)
  {
    var safe_search = '1';
    if (!userSettings.disableSafeSearch)
      safe_search = '3';
    return 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=' + this.getApiKey() + '&format=json&text=' + encodeURIComponent(query) + '&privacy_filter=interestingness-desc&safe_search='+safe_search+'&per_page=10&page=' + this._searchPage + '&jsoncallback=?&extras=o_dims,owner_name&sort=relevance';
  },

  clearSearch: function()
  {
    $('#results').empty();
    $('#pager').empty();
  } ,

  getApiKey: function()
  {
    return '58fa746f5973b117b63051c3b3d197be';
  },

  handleNoResults: function(numForCurrentP)
  {
    if (numForCurrentP == 0)
    {
      if (searcher._imageWrapper.returned_count == 2 && !searcher._imageWrapper.have_results)
      {
        $('#results').html(searcher.getNoResultsDisplay());
      }
      else{
        searcher._imageWrapper.returned_count++;
      }
    }
    else
      this.have_results = true;
  },

  search : function(qry, callbackP)
  {
    this.numResults = 0;
    this.startTime = (new Date()).getTime();
    //GOOGLE
    $.getJSON('http://ajax.googleapis.com/ajax/services/search/images?q=' + qry + '&v=1.0&start='+this._searchPage*8+'&rsz=large&lr=en&callback=?&', function(data){
      var div = $('#results');
      var len = data.responseData.results.length;
      $('#searchingflickr').hide('fast');
      this.numResults += len;
      for(var i=0;i<len; i++)
      {
        var result = data.responseData.results[i];
        div.append('<div class="imagedisplay"><a href="'+result.unescapedUrl+'" class="launchimage" target="_blank" title="View picture"></a><a class="thumbpreview" href="'+result.originalContextUrl+'" target="_blank" imgurl="'+result.url+'"><img src="'+result.tbUrl+'" border="0" align="top" width="'+(parseInt(result.tbWidth)*1.3)+'" height="'+(parseInt(result.tbHeight)*1.3)+'" /><br /><span style="position:absolute;bottom:7px;width: 240px;left:2px;"><span style="color:#555">'+result.contentNoFormatting+'</span><br />'+result.visibleUrl+' ('+result.width+'x'+result.height+')</span></a></div>');
      }
      searcher._imageWrapper.handleNoResults(len);
    });

    //YAHOOO
    $.getJSON('http://boss.yahooapis.com/ysearch/images/v1/'+encodeURIComponent(qry)+'?appid=uZhhBfbV34FgwNft89oh5hwYBpO9fJVbxJZHYVR1UACfDUSle0EB070CB18D2CxiDz0DWrQ-&start='+this._searchPage*8+'&count=42&callback=?', function(data){
      var div = $('#results');
      var len = 0;
      if (data.ysearchresponse.resultset_images)
      {
        len = data.ysearchresponse.resultset_images.length;
        this.numResults += len;
        $('#searchingflickr').hide('fast');
        for(var i=0;i<len; i++)
        {
          var result = data.ysearchresponse.resultset_images[i];
          var referer = result.refererurl;
          var title = result.title;
          if (title.length > 20)
            title = title.substring(0, 20) + '...';
          if (referer && referer.length > 40)
            referer = referer.substring(0, 40);
          if (referer.indexOf("http://www") > -1)
            referer = referer.substring(11, referer.length);
          div.append('<div class="imagedisplay"><a href="'+result.url+'" class="launchimage" target="_blank"></a><a class="thumbpreview" href="'+result.refererclickurl +'" target="_blank" imgurl="'+result.url+'"><img src="'+result.thumbnail_url+'" border="0" align="top" width="'+result.thumbnail_width+'" height="'+result.thumbnail_height+'" /><br /><span style="position:absolute;bottom:7px;width: 240px;left:2px;"><span style="color:#555">'+title+'</span><br />'+referer+' ('+result.width+'x'+result.height+')</span></a></div>');
        }
      }
      searcher._imageWrapper.handleNoResults(len);
    });

    //FLICKR
    $.getJSON(this.buildSearchUri(qry),
      function(data){
        $('#searchingflickr').hide('fast');
        if (data && data.photos && data.photos.photo && data.photos.photo.length > 0){
          searcher._imageWrapper.parseFlickrResult(data.photos.photo);
          this.numResults += data.photos.photo.length;

          // setup pager?
          if (data.photos.pages > 0){
            searcher._imageWrapper.displayPager(data.photos.pages);
          }
        }
        searcher._imageWrapper.handleNoResults(data.photos.photo.length);
      }
    );
 },

 displayPager: function(numPagesP)
  {
    var page = this._searchPage;
    var pager = "";
    if (page < 1)
      page = 1;
    else if (page > 1)
      pager += '<a href="#'+((page-1).toString())+'" onclick="javascript:searcher._imageWrapper.prevPage()" id="pagerPrev" title="Previous Page" class="havehistory">Prev</a>';
    else
      pager += '<span id="pagerPrev" class="nextprev">Prev</span>';
    var pages_shown = 0;
    var start_index = Math.max(1, page-5);
    for(var index=start_index; index<=numPagesP; index++)
    {
      if (page == index)
        pager += '<span href="#" title="Current Page" class="nextprev">' + index + '</span>';
      else
        pager += '<a href="#'+index+'" onclick="javascript:searcher._imageWrapper.loadPage(' + (index).toString() + ')" title="View Page ' + index + '" class="havehistory">' + index + '</a>';
      pages_shown++;
      if (pages_shown >= 10)
        break;
    }
    if (page < numPagesP)
      pager += '<a href="#'+(index+1).toString()+'" onclick="javascript:searcher._imageWrapper.nextPage()" id="pagerNext" title="Next Page">Next</a>';
    else
      pager += '<span id="pageNext" class="nextprev">Next</span>';
    $('#pager').html(pager);
    this.imagePreview();
  },

  imagePreview: function(){
    $("a.thumbpreview").hover(function(e){
      var page_width = $(document).width();
      var page_height = $(document).height();
      var x_offset = 5;
      var y_offset = -100;
      if (page_width - e.pageX < 400)
        x_offset = -600;
      if (page_height - e.pageY < 300)
        y_offset = -500;
      $(this).parent().css("border", "2px solid #8AC103");
      $(this).parent().css("color", "#8AC103");
      this.t = this.title;
      this.title = "";
      var c = (this.t != "") ? "<br/>" + this.t : "";
      $("body").append("<p id='thumbpreview'><img src='"+ $(this).attr("imgurl") +"' width='400' alt='Loading Image from Original Source...' />"+ c +"</p>");
      $("#thumbpreview")
        .css("top",(e.pageY + y_offset) + "px")
        .css("left",(e.pageX + x_offset) + "px")
        .fadeIn("fast");
      },
    function(){
      $(this).parent().css("border", "2px solid #ECECEC");
      $(this).parent().css("color", "#3E8EB3");

      this.title = this.t;
      $("#thumbpreview").remove();
      });
    $("a.thumbpreview").mousemove(function(e){
      var page_width = $(document).width();
      var page_height = $(document).height();
      var x_offset = 5;
      var y_offset = -100;
      if (page_width - e.pageX < 400)
        x_offset = -600;
      if (page_height - e.pageY < 300)
        y_offset = -500;

      $("#thumbpreview")
        .css("top",(e.pageY + y_offset) + "px")
        .css("left",(e.pageX + x_offset) + "px");
    });
  },

  setSearchPage: function(valueP)
  {
    if (valueP < 1)
      valueP = 1;
    this._searchPage = valueP;
  },

  parseFlickrResult : function(resultP)
  {
    this.endTime = (new Date()).getTime();
    $('#time').html("Search for " + searcher.search_query + "(" + (this.endTime - this.startTime) / 1000 + " seconds)");

    if (resultP)
    {
      var num = resultP.length;
      searcher.hideSearching();
      var div = $('#results');
      for(var index=0;index<num; index++)
      {
        var photo = resultP[index];
        var thumb_url = 'http://farm'+photo.farm+'.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'_m.jpg';
        var full_url = 'http://farm'+photo.farm+'.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'.jpg';
        var image_page_url = 'http://www.flickr.com/photos/' + photo.owner + '/' + photo.id;
        var title = photo.title;
        if (title.length > 30)
          title = title.substring(0, 30);
        var desc = '<span style="color:#555">'+title+'</span><br />'+photo.ownername+ ' ';
        if (photo.o_width)
          desc += '('+photo.o_width+'x'+photo.o_height+')';
        div.append('<div class="imagedisplay"><a href="'+full_url+'" class="launchimage" target="_blank"></a><a class="thumbpreview" href="'+image_page_url+'" target="_blank" imgurl="'+full_url+'"><img src="'+thumb_url+'" border="0" align="top" /><br /><span style="position:absolute;bottom:7px;width: 246px;left:2px;">'+desc+'</span></a></div>');
      }
    }
  },

  prevPage: function()
  {
    $('#results').empty();
    $('#pager').empty();
    searcher._imageWrapper._searchPage--;
    searcher._imageWrapper.search(searcher.search_query);
  },

  nextPage: function()
  {
    $('#results').empty();
    $('#pager').empty();
    searcher._imageWrapper._searchPage++;
    searcher._imageWrapper.search(searcher.search_query);
  },

  loadPage: function(pageP)
  {
    searcher._imageWrapper.clearSearch();
    searcher._imageWrapper._searchPage = pageP;
    searcher._imageWrapper.search(searcher.search_query);
  }
};

FlickrImageWrapper = function(engineP, onCompleteCallbackP)
{
  this._searchPage = 1;
};
FlickrImageWrapper.prototype =
{
  completedCallback : function(data)
  {
    this.parseResult(data);
  },

  buildSearchUri: function(query)
  {
    var safe_search = '1';
    if (!userSettings.disableSafeSearch)
      safe_search = '3';
    return 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=' + this.getApiKey() + '&format=json&text=' + encodeURIComponent(query) + '&privacy_filter=interestingness-desc&safe_search='+safe_search+'&per_page=50&page=' + this._searchPage + '&jsoncallback=?&owner_name%2C+icon_server%2C+views';
  },

  getApiKey: function()
  {
    return '58fa746f5973b117b63051c3b3d197be';
  },

  search : function(qry, callbackP)
  {
    this.startTime = (new Date()).getTime();
    $.getJSON(this.buildSearchUri(qry),
      function(data)
      {
        $('#searchingflickr').hide('fast');
        if (data && data.photos && data.photos.photo && data.photos.photo.length > 0)
        {
          searcher._imageWrapper.parseResult(data.photos.photo);

          // setup pager?
          if (data.photos.pages > 0)
          {
            searcher._imageWrapper.displayPager(data.photos.pages);
          }
        }
        else
        {
          $('#results').html(searcher.getNoResultsDisplay());
        }
      }
    );
 },

 displayPager: function(numPagesP)
  {
    var page = this._searchPage;
    var pager = "";
    if (page > 1)
      pager += '<a href="#" onclick="javascript:searcher._imageWrapper.prevPage()" id="pagerPrev" title="Previous Page">Prev</a>';
    else
      pager += '<span id="pagerPrev" class="nextprev">Prev</span>';
    var pages_shown = 0;
    var start_index = Math.max(1, page-5);
    for(var index=start_index; index<=numPagesP; index++)
    {
      if (page == index)
        pager += '<span href="#" title="Current Page" class="nextprev">' + index + '</span>';
      else
        pager += '<a href="#" onclick="javascript:searcher._imageWrapper.loadPage(' + (index).toString() + ')" title="View Page ' + index + '">' + index + '</a>';
      pages_shown++;
      if (pages_shown >= 10)
        break;
    }
    if (page < numPagesP)
      pager += '<a href="#" onclick="javascript:searcher._imageWrapper.nextPage()" id="pagerNext" title="Next Page">Next</a>';
    else
      pager += '<span id="pageNext" class="nextprev">Next</span>';
    $('#pager').html(pager);
  },

  setSearchPage: function(valueP)
  {
    this._searchPage = valueP;
  },

  parseResult : function(resultP)
  {
    this.endTime = (new Date()).getTime();
    $('#time').html("Search for " + searcher.search_query + "(" + (this.endTime - this.startTime) / 1000 + " seconds)");

    if (resultP)
    {
      var results = resultP;
      var num = results.length;
      searcher.hideSearching();
      var div = $('#results');
      div.empty();
      $('#pager').empty();
      var photo;
      for(var index=0;index<num; index++)
      {
        photo = results[index];
        var thumb_url = 'http://farm'+photo.farm+'.static.flickr.com/'+photo.server+'/'+photo.id+'_'+photo.secret+'_m.jpg';
        var image_page_url = 'http://www.flickr.com/photos/' + photo.owner + '/' + photo.id;
        div.append('<div class="imagedisplay"><a href="'+image_page_url+'" target="_blank"><img src="'+thumb_url+'" border="0" align="top" /><br />'+results[index].title+'</a></div>');
      }
    }
  },

  prevPage: function()
  {
    $('#results').empty();
    $('#pager').empty();
    searcher._imageWrapper._searchPage--;
    searcher._imageWrapper.search(searcher.search_query);
  },

  nextPage: function()
  {
    $('#results').empty();
    $('#pager').empty();
    searcher._imageWrapper._searchPage++;
    searcher._imageWrapper.search(searcher.search_query);
  },

  loadPage: function(pageP)
  {
    $('#results').empty();
    $('#pager').empty();
    searcher._imageWrapper._searchPage = pageP;
    searcher._imageWrapper.search(searcher.search_query);
  }
};


function youtubeVideoSearch()
{
  $.ajax({
      url: '/services/getVideos/',
      data: {
        'query': searcher.search_query,
        'page' : searcher.currentPage + 1
      },
      type: 'post',
      cache: false,
      dataType: 'json',
      success: function (result) {
        var div = $('#results');
        var len = 0;
        if (result)
        {
          var vids = result.videos;
          len = vids.length;
          searcher.hideSearching();
          div.empty();
          var pager = $('#pager');
          pager.empty();
          for (var i=0; i<len; i++)
            div.append('<div class="imagedisplay" style="text-align:center"><a href="'+vids[i].url+'" target="_blank">  <img src="'+vids[i].thumbnail+'" alt=""> <span style="position:absolute;bottom:7px;width: 240px;left:2px;"><span style="color:#555">'+vids[i].title+'</span><br />'+vids[i].length+' min </span></a></div>');

          if (result.total_videos > 50)
          {
            this.numPages = Math.ceil(result.total_videos/50);
            if (this.numPages > 20)
              this.numPages = 20;

            var page = this.currentPage;
            var content = "";
            if (page > 1)
              content += '<a href="/search/video/' + searcher.search_query + '/' + (page-1) + '/" id="pagerPrev" title="Previous Page">Prev</a>';
            else
              content += '<span id="pagerPrev" class="nextprev">Prev</span>';
            for(var index=1; index<=this.numPages; index++)
              content += '<a href="/search/video/' + searcher.search_query + '/' + (index-1).toString() + '/" title="View Page ' + index + '">' + index + '</a>';
            if (page < this.numPages)
              content += '<a href="/search/video/' + searcher.search_query + '/' +(page+1) +'/" id="pagerPrev" title="Previous Page">Prev</a>';
            else
              content += '<span id="pageNext" class="nextprev">Next</span>';

            $('#pager').append(pager);
          }
        }
        if (len == 0){
          // no results
          div.html(searcher.getNoResultsDisplay());
        }
      }
    });

  /*
  var url = 'http://gdata.youtube.com/feeds/api/videos?max-results=50&stat-index=0&orderby=viewCount&callback=?';
  $.ajax({
    url: url,
    type: 'get',
    cache: true,
    dataType: 'json',
    success: function (result) {
      if (result)
      {
        var vids = result.videos;
        var len = vids.length;
        searcher.hideSearching();
        var div = $('#results');
        div.empty();
        var pager = $('#pager');
        pager.empty();
        for (var i=0; i<len; i++)
          div.append('<div class="imagedisplay" style="text-align:center"><a href="'+vids[i].url+'" target="_blank">  <img src="'+vids[i].thumbnail+'" alt=""> <span style="position:absolute;bottom:7px;width: 240px;left:2px;"><span style="color:#555">'+vids[i].title+'</span><br />'+vids[i].length+' min </span></a></div>');

        if (result.total_videos > 50)
        {
          this.numPages = Math.ceil(result.total_videos/50);
          if (this.numPages > 20)
            this.numPages = 20;

          var page = this.currentPage + 1;
          var pager = "";
          if (page > 1)
            pager += '<a href="/search/video/' + searcher.search_query + '/' + (page-1) + '/" id="pagerPrev" title="Previous Page">Prev</a>';
          else
            pager += '<span id="pagerPrev" class="nextprev">Prev</span>';
          for(var index=1; index<=this.numPages; index++)
            pager += '<a href="/search/video/' + searcher.search_query + '/' + (index-1).toString() + '/" title="View Page ' + index + '">' + index + '</a>';
          if (page < this.numPages)
            pager += '<a href="/search/video/' + searcher.search_query + '/' +(page+1) +'/" id="pagerPrev" title="Previous Page">Prev</a>';
          else
            pager += '<span id="pageNext" class="nextprev">Next</span>';

          $('#pager').append(pager);
        }
      }
    }
  });  */
}

function LiveSearchClass() { };

LiveSearchClass.prototype.search = function(query, engine)
{
    // Returns search results from search.live.com
    //
    // query: The query term for the search engine (default=cheese)
    // count: The number of results returned from the search engine (default=10)
    // first: The offset result for the query (default=0)
    //  lang: The UI culture language (default=en-us)
    // adult: The adult settings [off/strict/moderate] (default=off)
    var trimQuery = this.__trimParamValue(query);
    if (trimQuery == "") throw "You must provide a query!";
    var count = userSettings.numMSNResults;
    var adult = 'strict';
    if (userSettings.disableSafeSearch)
      adult = 'off';

    var url = "http://search.live.com/json.aspx?q=" + escape(trimQuery);
    url += "&lang=en-us&adlt=strict&count=" + parseInt(count);
    url += "&first=0&sourcetype=web&form=popfly&adult="+adult;

    $.getScript(url,
      function()
      {
        try
        {
          var data = LiveSearchGetResponse();
          if (data && data.web)
          {
            data = data.web.results;

            var weight = userSettings.msnWeight/100;
            var len = data.length;
            var r = data;
            var new_result;
            for(var i=0; i<len; i++)
            {
              new_result = new SearchResult(r[i].url, r[i].title, r[i].description, SearchEngineEnum.MSN, i+1, r[i].displayUrl, r[i].cacheUrl, -1, "");
              new_result.score = (Math.pow(1.3,(10-i)) * weight);
              engine.addResult(new_result);
            }
          }
          searcher.callbackEngineWebSearchComplete(SearchEngineEnum.MSN);
        }
        catch (e)
        {
          searcher.callbackEngineWebSearchComplete(SearchEngineEnum.MSN);
        }
        searcher.havemsn = true;
      }
    );
    setTimeout("handleMSNTimeout()", 6000);

    return;
};

// function to trim parameters
LiveSearchClass.prototype.__trimParamValue = function(paramValue)
{
    if(!paramValue)
    {
        return "";
    }
    else if (!isNaN(paramValue))
    {
        return paramValue;
    }

    return paramValue.trim();
};

// function to get the user language
LiveSearchClass.prototype.__getUserLanguage = function()
{
    var lang = "";
    if (navigator.userAgent.indexOf("Firefox") != -1)
        lang = navigator.language;
    else if (navigator.userAgent.indexOf("MSIE") != -1)
        lang = navigator.browserLanguage;
    else
        lang = "en-us";

    return lang;
};

function handleVoteCheckTimeout()
{
  if (!searcher.haveScour)
    searcher.callbackEngineWebSearchComplete(SearchEngineEnum.Scour);
}

function handleGoogleTimeout()
{
  if (!searcher.haveGoogle)
    searcher.callbackEngineWebSearchComplete(SearchEngineEnum.Google);
}
function handleOneRiotTimeout()
{
  if (!searcher.haveOneRiot)
    searcher.callbackEngineWebSearchComplete(SearchEngineEnum.OneRiot);
}
function handleYahooTimeout()
{
  if (!searcher.haveYahoo)
    searcher.callbackEngineWebSearchComplete(SearchEngineEnum.Yahoo);
}
function handleMSNTimeout()
{
  if (!searcher.haveMSN)
    searcher.callbackEngineWebSearchComplete(SearchEngineEnum.MSN);
}

var feedback = {
	message: null,
	open: function (dialog) {
		// add padding to the buttons in firefox/mozilla
		if ($.browser.mozilla) {
			$('#feedback-container .feedback-button').css({
				'padding-bottom': '2px'
			});
		}
		// input field font size
		if ($.browser.safari) {
			$('#feedback-container .feedback-input').css({
				'font-size': '.9em'
			});
		}

		var title = $('#feedback-container .feedback-title').html();
		$('#feedback-container .feedback-title').html('Loading...');
		dialog.overlay.fadeIn(200, function () {
			dialog.container.fadeIn(200, function () {
				dialog.data.fadeIn(200, function () {
					$('#feedback-container .feedback-content').animate({
						height: 450
					}, function () {
						$('#feedback-container .feedback-title').html(title);
						$('#feedback-container form').fadeIn(200, function () {
							$('#feedback-container #feedback-name').focus();

							// fix png's for IE 6
							if ($.browser.msie && $.browser.version < 7) {
								$('#feedback-container .feedback-button').each(function () {
									if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
										var src = RegExp.$1;
										$(this).css({
											backgroundImage: 'none',
											filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src + '", sizingMethod="crop")'
										});
									}
								});
							}
						});
					});
				});
			});
		});
	},
	show: function (dialog) {
		$('#feedback-container .feedback-send').click(function (e) {
			e.preventDefault();
			// validate form
			if (feedback.validate()) {
				$('#feedback-container .feedback-message').fadeOut(function () {
					$('#feedback-container .feedback-message').removeClass('feedback-error').empty();
				});
				$('#feedback-container .feedback-title').html('Sending...');
				$('#feedback-container form').fadeOut(200);
				$('#feedback-container .feedback-content').animate({
					height: '80px'
				}, function () {
					$('#feedback-container .feedback-loading').fadeIn(200, function () {
						$.ajax({
							url: '/feedback/send',
							data: $('#feedback-container form').serialize(),
							type: 'post',
							cache: false,
							dataType: 'json',
							complete: function (xhr) {
								$('#feedback-container .feedback-loading').fadeOut(200, function () {
									$('#feedback-container .feedback-title').html('Thank you!');
									$('#feedback-container .feedback-message').html(xhr.responseText).fadeIn(200);
								});
							},
							error: feedback.error
						});
					});
				});
			}
			else {
				if ($('#feedback-container .feedback-message:visible').length > 0) {
					var msg = $('#feedback-container .feedback-message div');
					msg.fadeOut(200, function () {
						msg.empty();
						feedback.showError();
						msg.fadeIn(200);
					});
				}
				else {
					$('#feedback-container .feedback-message').animate({
						height: '30px'
					}, feedback.showError);
				}

			}
		});
	},
	close: function (dialog) {
		$('#feedback-container .feedback-message').fadeOut();
		$('#feedback-container .feedback-title').html('Thanks!');
		$('#feedback-container form').fadeOut(200);
		$('#feedback-container .feedback-content').animate({
			height: 40
		}, function () {
			dialog.data.fadeOut(200, function () {
				dialog.container.fadeOut(200, function () {
					dialog.overlay.fadeOut(200, function () {
						$.modal.close();
					});
				});
			});
		});
	},
	error: function (xhr) {
//		alert(xhr.statusText);
	},
	validate: function () {
		feedback.message = '';
		if (!$('#feedback-container #feedback-name').val()) {
			feedback.message += 'Name is required. ';
		}

		var email = $('#feedback-container #feedback-email').val();
		if (!email) {
			feedback.message += 'Email is required. ';
		}
		else {
			if (!feedback.validateEmail(email)) {
				feedback.message += 'Email is invalid. ';
			}
		}

    if (!$('#feedback-container #feedback-section').val())
    {
      feedback.message += 'Topic is required.';
    }

		if (!$('#feedback-container #feedback-message').val()) {
			feedback.message += 'Message is required.';
		}

		if (feedback.message.length > 0) {
			return false;
		}
		else {
			return true;
		}
	},
	validateEmail: function (email) {
		var at = email.lastIndexOf("@");

		// Make sure the at (@) sybmol exists and
		// it is not the first or last character
		if (at < 1 || (at + 1) === email.length)
			return false;

		// Make sure there aren't multiple periods together
		if (/(\.{2,})/.test(email))
			return false;

		// Break up the local and domain portions
		var local = email.substring(0, at);
		var domain = email.substring(at + 1);

		// Check lengths
		if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
			return false;

		// Make sure local and domain don't start with or end with a period
		if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
			return false;

		// Check for quoted-string addresses
		// Since almost anything is allowed in a quoted-string address,
		// we're just going to let them go through
		if (!/^"(.+)"$/.test(local)) {
			// It's a dot-string address...check for valid characters
			if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
				return false;
		}

		// Make sure domain contains only valid characters and at least one period
		if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
			return false;

		return true;
	},
	showError: function () {
		$('#feedback-container .feedback-message')
			.html($('<div class="feedback-error">').append(feedback.message))
			.fadeIn(200);
	}
};

function showdemo(mypopurl,mypopname,sizew,sizeh,poppos,auFoyer){
  var fenetre;
  if(poppos=="center"){magauche=(screen.width)?(screen.width-sizew)/2:100;monhaut=(screen.height)?(screen.height-sizeh)/2:100;}
  else if((poppos!='center') || poppos==null){magauche=+0;monhaut=+0}
    reglages="width=" + sizew + ",height=" + sizeh + ",top=" + monhaut + ",left=" + magauche + ",scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=yes";fenetre=window.open(mypopurl,mypopname,reglages);
    fenetre.focus();
}

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }

        output = Base64._utf8_decode(output);
        return output;
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
};

/* Validation */

var errorMsg = {
  'length':'Please enter a longer comment, a minimum of 30 characters.',
  'repeatlines':'Your comment plays like a broken record. Please update your comment.',
  'repeatletters':'What is "#offense#"? Please update your comment, thanks!',
  'sparsevowels':'What is "#offense#"? Please update your comment, thanks!',
  'wordrepeat':'Woah, too much repetition, please be more detailed',
  'manysymbols':'That\'s a lot of symbols. Please update your comment, thanks!',
  'repeatsymbols':'What is "#offense#"? Please update your comment, thanks!',
  'repeatnumbers':'What is "#offense#"? Please update your comment, thanks!',
  'linebreaks':'That is a lot of lines for that much content.',
  'manylinks':'You\'re posting too many links.',
  'wordlengthtoolong': 'What is "#offense#"? Please update your comment, thanks!',
  'urllengthtoolong': 'Very sorry but we do not allow urls longer than 100 characters.'
};




function watchTextarea(el) {
  var par = el.parent();
  var txt = el;

  par.find('.addCommentPostPos').click(function(e){
    e.preventDefault();
    $(this).hide();
    var comment = txt.val();
    if (!validateComment(comment))
    {
      $(this).show();
      return false;
    }

    var url = (par.parent().parent().find(".resultUrl").text());

    var commentLength = comment.replace(/ /g, '').length;
    if (commentLength < 30 || commentLength > 500)
    {
      par.find('.addCommentErrorsText').text('Your comment must be between 30 and 500 characters.');
      par.find('.addCommentErrors').show();
      $(this).show();
    }
    else
    {
      par.find('.addCommentErrorsText').text('');
      par.find('.addCommentErrors').hide();
      addComment(comment, url, 1, txt, $(this));
    }
  });

  par.find('.addCommentPostNeg').click(function(e){
    e.preventDefault();
    $(this).hide();
    var comment = txt.val();
    if (!validateComment(comment)) {
      $(this).show();
      return false;
    }

    var url = (par.parent().parent().find(".resultUrl").text());

    var commentLength = comment.replace(/ /g, '').length;
    if (commentLength < 30 || commentLength > 500)
    {
      par.find('.addCommentErrorsText').text('Your comment must be between 30 and 500 characters.');
      par.find('.addCommentErrors').show();
      $(this).show();
    }
    else
    {
      par.find('.addCommentErrorsText').text('');
      par.find('.addCommentErrors').hide();
      addComment(comment, url, 0, txt, $(this));
    }
  });

  function triggerError(errorKey, offense) {
    var err;
    if(offense!=undefined) {
      err = errorMsg[errorKey].replace(/#offense#/g,offense);
    } else {
      err = errorMsg[errorKey];
    }
    par.find('.addCommentErrorsText').text(err);
    par.find('.addCommentErrors').show();
  }

  function clearError() {

    par.find('.addCommentErrorsText').text('');
    par.find('.addCommentErrors').hide();
    par.find('.addCommentPosted').hide();
  }

  function validateComment(comment)
  {
    var commentLines = comment.split('\n').length;
    var commentLength = comment.replace(/ /g, '').length;
    // Extract URLs
    var commentUrls = comment.match(/http[^ ]+/gi);
    // Remove URLs from data we'll be testing
    comment = comment.replace(/http[^ ]+/gi,' ');
    var commentWords = comment.split(' ');
    for(var i=0; i<commentWords.length; i++)
      commentWords[i] = commentWords[i].toString();

    clearError();

    // Comment length between 30-500
    par.find('.currentCharacters').text(commentLength.toString());
    if(commentLength < 30 || commentLength > 500) {
      par.find('.addCommentCharacters').removeClass('addCommentCharactersGood');
      par.parent().find('.addCommentPostNeg').removeClass('addCommentPostNegGood');
      par.parent().find('.addCommentPostPos').removeClass('addCommentPostPosGood');
    }
    else {
      par.find('.addCommentCharacters').addClass('addCommentCharactersGood');
      par.parent().find('.addCommentPostNeg').addClass('addCommentPostNegGood');
      par.parent().find('.addCommentPostPos').addClass('addCommentPostPosGood');
    }

    // check url lengths
    for(var x in commentUrls)
    {
      if (commentUrls[x].length > 100)
      {
        triggerError('urllengthtoolong',commentUrls[x]);
        return false;
      }
    }

    // check word lengths
    for (var x in commentWords)
    {
      if (commentWords[x].length > 35)
      {
         triggerError('wordlengthtoolong',commentWords[x]);
        return false;
      }
    }

    // Update Comment Length Counter
    par.find('.currentCharacters').text(commentLength.toString());

    // Repetitive Characters - 4 in a row
    var repetitiveChars = comment.match(/([^ ])\1\1\1/g);
    if(repetitiveChars) {
      for(var x in commentWords) {
        if(commentWords[x].toString().indexOf(repetitiveChars[0])>=0) {
          var letOffense = commentWords[x];
          if(letOffense != undefined) {
            break;
          }
        }
      }
      if(letOffense!=undefined) {
        triggerError('repeatletters',letOffense);
        return false;
      }
    }

    // Repetitive Numbers - Including spaces
    var repetitiveNumbers = comment.replace(/ /g,'').match(/[0-9 ]{6,}/g);
    if(repetitiveNumbers) {
      var numOffense = repetitiveNumbers[0];
      triggerError('repeatnumbers',numOffense);
      return false;
    }

    // Repetitive Words
    // Remove all spaces and then check
    if(comment.replace(/ /g,'').match(/([a-z]{2,})\1\1/gi)) {
      triggerError('wordrepeat');
      return false;
    }

    // Repeating Consonants
    var repeatConsonants = comment.match(/([qwrtplkjhgfdszxcvbnm]{5,})/gi);
    if(repeatConsonants) {
      for(var x in commentWords) {
        if(commentWords[x].toString().indexOf(repeatConsonants[0])>=0) {
          var vowelOffense = commentWords[x];
          break;
        }
      }
      triggerError('sparsevowels',vowelOffense);
      return false;
    }

    // More than 10 non-punctuation symbols
    if(comment.replace(/[a-z0-9 \.\,\?\!\(\)\;\:\/]/gi,'').length>10) {
      triggerError('manysymbols');
      return false;
    }

    // 4+ Repeating Symbols
    var repeatingSymbols = comment.replace(/ /g,'').match(/([^a-z0-9\/\.\,\?\!\(\)\;\:\\\n/]{4,})/i);
    if(repeatingSymbols) {
      var symbolOffense = repeatingSymbols[0];
      triggerError('repeatsymbols',symbolOffense);
      return false;
    }

    // More than 3 links
    if(commentUrls) {
      if(commentUrls.length>3) {
        triggerError('manylinks');
        return false;
      }
    }

    // Too many line breaks
    // Must average 15 characters per line
    if(commentLines > 3 && (commentLength/commentLines)<15) {
      triggerError('linebreaks');
      return false;
    }

    // Repetitive Lines
    var repeatLines = comment.match(/^(.*)\n\1\n\1/gm);
    if(repeatLines) {
      triggerError('repeatlines');
      return false;
    }
    return true;
  }

  $(el).keydown(function(e){
    if ((e.which != 86 && !e.ctrlKey) || !e.ctrlKey)
      validateComment($(this).val());
    });
}

// filter tool wiring
$(document).ready(function(){
  var searchbar = $('#txtSearch');
  $('#filter').css('opacity',0.90);

  // Set a flag so we can't open a filter while filtering
  var filterShown = false;
  $('#results').dblclick(function(e){
    if(filterShown) {
      return;
    }
    var clickPosition = {x:e.pageX,y:e.pageY};

    // Get the word they selected
    var word = $.trim(getSelected());

    // If they selected a bunch of words, abort mission
    if(word.match(/\s+/g)) {
      return;
    }

    // If their word is less than 3 characters, abort mission
    if(word.length < 3) {
      return;
    }

    var top = clickPosition.y + 9;

    var left = clickPosition.x - 88;
    if (left <= 20)
      left = 20;

    $('#filter').css({
      'top': top+"px",
      'left': left+"px"
    });

    $('#filterKeyword').val(word);

    $('#filter').show('fast');
    filterShown = true;
  });

  $(document).click(function(e){
    if(!filterShown) {
      return;
    }

    if(e.target.id=='filter' || e.target.parentNode.id=='filter') {
      return;
    }

    hideFilter();
  });

  $('#filterInclude').click(function(e){
    e.preventDefault();
    var kw = $('#filterKeyword').val();

    // Check and make sure keyword doesn't already exist, or is excluded
    var q = searchbar.val();
    var qbits = q.split(' ');
    var nq = [];
    var added = false;
    for(var i=0;i<qbits.length; i++) {
      var qb = qbits[i];
      if(qb.toLowerCase()==kw.toLowerCase()) {
        return;
      }
      if(qb.toLowerCase()=="-"+kw.toLowerCase()) {
        nq.push(kw);
        added = true;
      } else {
        nq.push(qb);
      }
    }

    if(!added) {
      nq.push(kw);
    }

    searchbar.val(nq.join(' '));
    hideFilter();
    window.location.href = '/search/web/'+nq.join(' ')+'/related/';
  });

  $('#filterExclude').click(function(e){
    e.preventDefault();
    var kw = $('#filterKeyword').val();

    // Check and make sure keyword doesn't already exist, or is excluded
    var q = searchbar.val();
    var qbits = q.split(' ');
    var nq = [];
    var added = false;
    for(var i=0;i<qbits.length; i++) {
      var qb = qbits[i];
      if(qb.toString().toLowerCase()=="-"+kw.toLowerCase()) {
        return;
      }
      if(qb.toString().toLowerCase()==kw.toLowerCase()) {
        nq.push("-"+kw);
        added = true;
      } else {
        nq.push(qb);
      }
    }

    if(!added) {
      nq.push("-"+kw);
    }

    searchbar.val(nq.join(' '));
    hideFilter();
    window.location.href = '/search/web/'+nq.join(' ')+'/related/';
  });

  function hideFilter() {
    filterShown = false;
    $('#filter').hide('fast');
  }

  $("#filterKeyword").hover(
      function () {
        $(this).css("borderColor", "#f0f0f0");
      },
      function () {
        $(this).css("borderColor", "#fff");
      }
    );
  $("#filterKeyword").focus(
      function () {
        $(this).css("borderColor", "#f0f0f0");
      },
      function () {
        $(this).css("borderColor", "#fff");
      }
    );
  $('#filterClose').click(function(){
    hideFilter();
  });
});

//report comment
$(document).ready(function(){
  $('#reportform-submit').click(function(){
    $.ajax({
      url: '/services/reportcomment/',
      data: {
        'commentid': $('#reportform-commentid').text(),
        'reportcomment-type' : $("input[@name='abusetype']:checked").val(),
        'message' : $('#report-form-info').val()
      },
      type: 'post',
      cache: false,
      dataType: 'json',
      success: function () {
        $.modal.close();
      }
    });
  });
});

//login form
$(document).ready(function(){
  $('#loginform-join').click(function(){
    window.location.href = '/signup/';
  });

  $('#header_signin').click(function(e){
    e.preventDefault();
    showLoginModal();
  });

  $('#loginform-login').click(function(e){
    e.preventDefault();
    $.ajax({
      url: '/services/login/',
      data: {
        'username': $('#login-username').val(),
        'password' : $("#login-password").val()
      },
      type: 'post',
      cache: false,
      dataType: 'json',
      success: function (data) {
        if (data.success)
        {
          userSettings.userid = data.id;
          userSettings.username = data.username;
          cookies.saveSettings();
          $("#sign_in_user").hide();
          $("#new_user").hide();
          $("#welcome_user_name").html(userSettings.username);
          $("#welcome_user").show();
          $("#points_logout").show();
          getUserPoints();
          searcher.loadElements();
          searcher.search(gTerm);

          $.modal.close();
        }
        else
          $('#loginform-error').text(data.message);
      }
    });
  });

  // handle enter/esc
  $('#login-username, #login-password').keydown(function(e){
    if(e.keyCode == 27)
      $.modal.close();
    else if (e.keyCode == 13)
      $('#loginform-login').click();
  });
});

function showLoginModal()
{
  $("#loginmodal").modal({
      close: false,
      overlayId: 'login-overlay',
      containerId: 'login-container',
      onOpen: login_screen.open
    });

    $('#login-username').focus();
}

var login_screen = {
  open: function(dialog)
  {
    dialog.overlay.fadeIn(300, function () {
        dialog.container.fadeIn(300, function () {
          dialog.data.fadeIn(300, function () { });
        });
    });
  }
};

function getSelected() {
  var word;
  if($.browser.msie) {
    word = document.selection.createRange().text;
    document.selection.empty();
    return word;
  } else {
    return window.getSelection()+'';
  }
}

function numberFormatWithCommas(inputP)
{
	inputP += '';
	var x = inputP.split('.');
	var x1 = x[0];
	var x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

  function handleSearchPage()
	  {
	    var txtB = $('#txtSearchB').get(0);
	    txtB.value = gTerm;
	    var txt = $('#txtSearch').get(0);
//	    txt.focus();
	    txt.value = window.gTerm;

      searcher.loadElements();
      searcher.setSearchType(gType);
      searcher.currentPage = gPage;
      searcher.search(gTerm);

	  var nSearchContainer = $('#nSearch-container')[0];
	  $('#nSearch-tabs div').click(function(e){
        nSearchContainer.className = 'nSearch'+this.id.match(/-./)[0];
  	    var val = $('#txtSearch').val();
	    if (val.trim() != '')
	    {
	      $.scour.homepage.search();
	    }
	  });
      var nSearchContainer_bottom = $('#nSearch-containerB')[0];
	  if (nSearchContainer_bottom) {
	    $('#nSearch-tabsB div').click(function(e){
	      nSearchContainer_bottom.className = 'nSearch' + this.id.match(/-./)[0];
  		  var val = $('#txtSearchB').val();
		  if (val.trim() != '')
		  {
		    $.scour.homepage.search('B');
		  }
		});
	  }
		  $("#nSearch-button").click(function(e){
		    e.preventDefault();
		    $.scour.homepage.search();
		  });

		  $("#nSearch-buttonB").click(function(e){
		    e.preventDefault();
		    $.scour.homepage.search('B');
		  });


	    if (!userSettings.surveyVisited)
	      $("#topcornerfeedback").show();

	    try { document.title = gTerm + " - Scour Search"; }
      catch(e){}

      if (userSettings.username != '')
      {
        $("#welcome_user_name").html(userSettings.username);
        $("#welcome_user").show();
        $("#points_logout").show();
      }
      else
      {
        $("#sign_in_user").show();
        $("#new_user").show();
      }

      /*if (gSubID != "4" && gSubID != "11"){
        if (Number(gSubID) > 0 && userSettings.showpostfirstsearchpopup && !userSettings.isLoggedIn())
        {
          showSignupModal();
        }
        else if (userSettings.showpostfirstsearchpopup && !userSettings.isLoggedIn())
  	    {
          if (userSettings.introSearches == 3)
            setTimeout('showSignupPopup();', 2000);
          else if (userSettings.introSearches < 4)
          {
            userSettings.introSearches++;
            cookies.saveSettings();
          }
        }
      }*/

      if (userSettings.showSerpsRealtimeNoticePsst)
      {
        $('#scour-tip').fadeIn('slow');
      }

      $('#pager-count-close-tip').click(function(e){
        e.preventDefault();
        userSettings.showPageNumberHint = false;
        cookies.saveSettings();
        $('#pagerinfo').fadeOut('slow');
      });

      $('.scour-tip-close, #psstInvites').click(function(e){
        e.preventDefault();
        $('#scour-tip').fadeOut('slow');
        userSettings.showSerpsRealtimeNoticePsst = false;
        cookies.saveSettings();
      });

      $('#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();
					}
				});
      });


		// Initialize history plugin.
		// The callback is called at once by present location.hash.
		$.historyInit(searchPageLoaded, window.location.href);

		// set onlick event for buttons
		$(".havehistory").live("click", function(){
			//
			var hash = this.href;
			hash = hash.replace(/^.*#/, '');
			$.historyLoad(hash);
			return false;
		});
  }

  function searchPageLoaded(hash)
  {
    var page_index = Number(hash);
    if (searcher.searchType == 'web')
    {
      searcher.showPage(page_index-1);
    }
    else if (searcher.searchType == 'images')
      searcher._imageWrapper.loadPage(page_index);
  }

  function showSignupPopup()
  {
    $('#wannasignup').modal(
     {
       overlayId: 'wannasignup-overlay',
      containerId: 'wannasignup-container'
     }
   );

   $('#wannasignup-close, #wannasignup-no').click(function(e){
     e.preventDefault();
     userSettings.showpostfirstsearchpopup = false;
     cookies.saveSettings();
     $.modal.close();
   });
   $('#wannasignup-overlay').click(function(){
     $.modal.close();
   });


   $('#wannasignup-yes').click(function(e){
     e.preventDefault();
     $.modal.close();
     showSignupModal();
   });
  };

  function showSignupModal()
  {
     $('#signupinitial').modal(
       {
         overlayId: 'signup-overlay',
         onClose: showPostFirstSearchPopupClose,
         onOpen: showPostFirstSearchPopupOpen
       }
     );
    $('#signupinitial').html('<center><iframe id="signupinitialpopup" height="700" width="730" frameborder="0" marginwidth="0" src="http://scour.com/signup/popup"></iframe></center>');
  };

  function closeSignupPopup()
  {
    userSettings.showpostfirstsearchpopup = false;
    cookies.saveSettings();
    $.modal.close();
  };

	function showPostFirstSearchPopupOpen(dialog)
  {
    dialog.overlay.fadeIn(200); /*, function () {
			dialog.container.fadeIn(200, function () {*/
      var h = 710;
      if ($(window).height() < h + 50)
        h = $(window).height() - 50;
      dialog.container.animate({height: h });

      $("#signupinitialpopup").animate({height: h});
				/*dialog.data.fadeIn(200, function () {*/
			$('#signupinitial').animate({height: h/2 });
			  /*
				});
			});
		});*/
  };

	function showPostFirstSearchPopupClose(dialog) {
    userSettings.showpostfirstsearchpopup = false;
    cookies.saveSettings();
    dialog.data.fadeOut('slow', function () {
      dialog.container.slideUp('slow', function () {
        dialog.overlay.fadeOut('slow', function () {
          $.modal.close(); // must call this to have SimpleModal
                           // re-insert the data correctly and
                           // clean up the dialog elements
        });
      });
    });
  };

function gaSSDSLoad (acct) {
  var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."),
      pageTracker,
      s;
  s = document.createElement('script');
  s.src = gaJsHost + 'google-analytics.com/ga.js';
  s.type = 'text/javascript';
  s.onloadDone = false;
  function init () {
    pageTracker = _gat._getTracker(acct);
    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);
}