var timer1;
var timer2;
var last_twitter_max_id=-1;
var last_twitter_refresh_url='';
var last_twitter_newcount=0;
var last_rsearch_newcount=0;
var last_currsearch_newcount=0;
var current_search_timestamp = new Date();

$(document).ready(function() {

   other_results_ui_init();

   $('#rsearch_new_status').hover(function(e){	
      $("#rsearch_new_status").stop().animate({ backgroundColor: "#FFCC33"}, 300).animate({ backgroundColor: "#f5f3ef"}, 1000);
      $("#recent_searches").stop().animate({ backgroundColor: "#FFCC33"}, 300).animate({ backgroundColor: "#FFFFFF"}, 1000);
      $("#recent_search_count").stop().animate({ backgroundColor: "#FFCC33"}, 300).animate({ backgroundColor: "#f5f3ef"}, 1000);
    },
    function(){
      $("#recent_searches").stop().animate({ backgroundColor: "#FFFFFF"}, 100);
      $("#rsearch_new_status").stop().animate({ backgroundColor: "#f5f3ef"}, 100);
      $("#recent_search_count").stop().animate({ backgroundColor: "#f5f3ef"}, 100);
   });

   $('#twitter_new_status').hover(function(e){	
      $("#twitter_search").stop().animate({ backgroundColor: "#FFCC33"}, 300).animate({ backgroundColor: "#FFFFFF"}, 1000);
      $("#twitter_new_status").stop().animate({ backgroundColor: "#FFCC33"}, 300).animate({ backgroundColor: "#f5f3ef"}, 1000);
      $("#twitter_search_count").stop().animate({ backgroundColor: "#FFCC33"}, 300).animate({ backgroundColor: "#f5f3ef"}, 1000);
    },
    function(){
      $("#twitter_search").stop().animate({ backgroundColor: "#FFFFFF"}, 100);
      $("#tter_new_status").stop().animate({ backgroundColor: "#f5f3ef"}, 100);
      $("#twitter_search_count").stop().animate({ backgroundColor: "#f5f3ef"}, 100);
   });
$(".premiumQ").click(showPremiumAdDialog);
/*
   $('#currsearch_new_status').hover(function(e){	
      $("#centercolumn").stop().animate({ backgroundColor: "#FFCC33"}, 300).animate({ backgroundColor: "#FFFFFF"}, 1000)
    },
    function(){
      $("#centercolumn").stop().animate({ backgroundColor: "#FFFFFF"}, 100);
   });
*/
});
 
function showPremiumAdDialog() {
        var id=$(this).attr("id").split(":");
        console.log(id[1]);
        Soruka.Search.Dialog.showSearch( id[1],'a','','{}',1,0 );
        return false;
}
function timer1Task() {
   clearTimeout(timer1);
   twitterSearch();
   if ($('#q-sm').length)
      timer1 = setTimeout('timer1Task()', timer1Task.interval);
};

function timer2Task() {
   clearTimeout(timer2);
   recentSearches();
   if ($('#q-sm').length)
      timer2 = setTimeout('timer2Task()', timer2Task.interval);
};

function trending() {
   var now = new Date();
   $.getJSON("gettrends.php", {nt: (now.getTime())},  function(obj){
      if (isEmpty(obj)) {
           // some error happened while parsing, do nothing and exit.
           $('#num_trends').html(" (none*)");
           return;
      }
      var results = '<ul style="list-style:disc;margin-left:0;list-style-position:outside;">';
      var count = obj.count;
      $.each(obj.terms, function(n,val){
         link = '?q='+val+'&orig=ma';
         results += '<li class="trends_li"><a class="recent_search" title="Search \''+val+'\'" rel="nofollow" href="'+link+'">'+val+'</a></li>';
      });
      results += '</ul>';
      $('#num_trends').html(" (Top "+count+")");
      $('#trending_content').html(results);
      $("#main_content").equalHeights(true);
   });
}

function recentSearches() {
   if ( !$("input#q-sm")[0]) // if on main homepage, do nothing
      return;

   getRecentSearchesCount();
};

function getRecentSearchesCount() {
   if (recentSearches.inProcess)
      return;
   recentSearches.inProcess = true;

   var now = new Date();
   $.getJSON("recent_searches.php", {cc: recentSearches.cont_cnt++, nt: (now.getTime())},  function(obj){
      recentSearches.inProcess = false;
      if (isEmpty(obj)) {
           // some error happened while parsing, do nothing and exit.
           $("#num_rsearches").html(' (none*)');
           timer2Task.interval = 60000;
           return;
      }
      var results = '<ul style="list-style:disc;margin-left:0;list-style-position:outside;">';

      timer2Task.interval = obj.interval;
      var fetch_count = 0;
      var total_new = 0;
      var current_search_count = 0;
      var current_search_title = '';
      var current_search_link = '';
      var tmpdate = new Date();
      $.each(obj.queries, function(n,val){
         if (n==0) { // 1st one special as it is the current query term
            current_search_title = val.term;
            current_search_link = val.url;
            current_search_count = val.count;
         } else { // skip 1st one which is the current search term
            var title = val.term;
            var link = val.url+'&orig=rs';
            var count = val.count;
            var lastQueryTS = val.lastQueryTS;
            var tsString = "Search '"+title+"' (last search on "+lastQueryTS+")";
            if (count > 0) // check for > 0 because negative value would indicate error condition for debugging use
               total_new += count;
            countstr = '';
            if (count > 0) // check for > 0 because negative value would indicate error condition for debugging use
               countstr = '('+number_format(count)+' new)'; 
            else if (count < 0) // error condition (e.g. server could not get query result/count for some reason)
               countstr = '*';
     
            results += '<li class="rsearch_li"><a class="recent_search" title="'+tsString+'" rel="nofollow" href="'+link+'">'+title+ 
                       '</a>  <span class="greyout"><nobr>'+countstr+'</nobr></span></li>';
            fetch_count++;
         }
      });

      results += '</ul>';

      if (fetch_count > 0)
         rsearch_cnt_str = '  (Recent '+fetch_count+')';
      else
         rsearch_cnt_str = '  (none)';

      $("#rsearches_content").html(results);
      $("#num_rsearches").html(rsearch_cnt_str);

      var right_now = new Date();
      var t1 = right_now.getTime();
      var t2 = current_search_timestamp.getTime();
      var elapse_time_ms = t1-t2;
      var days = Math.floor(elapse_time_ms / (1000 * 86400));
      elapse_time_ms -= days * (1000 * 86400)
      var hours = Math.floor(elapse_time_ms / (1000 * 3600));
      elapse_time_ms -= hours * (1000 * 3600);
      var mins = Math.floor(elapse_time_ms / (1000 * 60));
      elapse_time_ms -= mins * (1000 * 60);
      var secs = Math.floor(elapse_time_ms / 1000);

      var elapse_time_str = '';
      if (days > 0)
         elapse_time_str = days+(days > 1? " days ":" day ");
      if (hours > 0)
         elapse_time_str += hours+(hours > 1? " hrs ": " hr ");
      if ((mins > 0 && days < 1) || (mins > 0 && hours==0))
         elapse_time_str += mins+(mins > 1? " mins ":" min ");
/*
      if ((secs > 0 && hours < 1 && days < 1) || (secs > 0 && mins==0 && days < 1))
         elapse_time_str += secs+(secs > 1? " secs ":" sec ");
*/
      if (elapse_time_str != '')
         elapse_time_str = "in the last " + elapse_time_str;

      if (!recentSearches.first) {  // if first time, then must not be by timer, so ignore this block...
         if (current_search_count > last_currsearch_newcount) {
            var newstatus = '&#149;&nbsp;<span id="current_search_count" style="color: #ff0000;">'+
                            number_format(current_search_count)+'</span> more result'+(current_search_count>1? 's':'')+
                            ' for <em>"'+current_search_title+
                            '"</em>&nbsp;<span id="elapse_time"></span>&nbsp;<a title="click to get new results" style="font-size: 70%" rel="nofollow" href="'+
                            current_search_link+'">(refresh to see)</a>';
            $("#currsearch_new_status").html(newstatus);
            $("#current_search_count").css({ 'background-color': '#fdb664'}).animate({ backgroundColor: "#f5f3ef"}, 2000);
            last_currsearch_newcount = current_search_count;
         } else if (current_search_count == 0) {
            var newstatus = '&#149;&nbsp;No new results for "<em>'+current_search_title+'</em>"&nbsp;<span id="elapse_time"></span>';
            $("#currsearch_new_status").html(newstatus);
         }
         $("#elapse_time").html(elapse_time_str);
         $("#current_search_count").css({ 'background-color': '#f5f3ef'});
      } else
         recentSearches.first = false;

      if (total_new > last_rsearch_newcount) {
         var newstatus = '&nbsp;&#149;&nbsp;<span id="recent_search_count" style="color: #ff0000;">'+number_format(total_new)+'</span> more result'+(total_new>1? 's':'')+' from "Your Recent Searches"&nbsp;&#149;&nbsp;';
         $("#rsearch_new_status").html(newstatus);
         $("#recent_search_count").css({ 'background-color': '#fdb664'}).animate({ backgroundColor: "#f5f3ef"}, 2000);
         last_rsearch_newcount = total_new;
      } else if (total_new == 0) {
         var newstatus = '&nbsp;&#149;&nbsp;No new results from "Your Recent Searches"&nbsp;&#149;&nbsp;';
         $("#rsearch_new_status").html(newstatus);
      }
      $("#rsearch_new_status").css({ 'background-color': '#f5f3ef'});

      $("#main_content").equalHeights(true);
   });
};

function twitterSearch() {
   if ( !$("input#q-sm")[0]) // if on main homepage, do nothing
      return;
   getTweets();
};

function getTweets() {

   if (twitterSearch.inProcess)
      return;
   twitterSearch.inProcess = true;

   var theQuery = '?q='+urlencode($("input#q-sm")[0].value);
   if (last_twitter_refresh_url!='') // if this is a timer-driven refresh situation instead of a fresh query
      theQuery = last_twitter_refresh_url; // then use the refresh_url sent from twitter search.

   theQuery += '&lang=en';

   //alert('about to call ajax get');
   var now = new Date();
   $.getJSON("twitter_search.php", {query: theQuery, cc: twitterSearch.cont_cnt++, nt: (now.getTime())},  function(obj){
      twitterSearch.inProcess = false;
      if (isEmpty(obj)) {
           // some error happened while parsing, do nothing and exit.
           $("#numtweets").html(' (none*)');
           timer1Task.interval = 60000;
           return;
      }
      var results = '<ul style="list-style:none;margin-left:-10;list-style-position:outside;">';
      timer1Task.interval = obj.interval;

      if (last_twitter_max_id > 0) {
         if (last_twitter_max_id < obj.max_id) {
            // loop through statuses to count up to last max
            var newcount = 0;
            $.each(obj.results, function(n,val){
               newcount++;
            });

            if (newcount > 0) {
               last_twitter_newcount += newcount;
               var newstatus = '<span id="twitter_search_count" style="color: #ff0000;">'+number_format(last_twitter_newcount)+'</span> more tweet'+(newcount>1? 's':'')+
                               ' found&nbsp;<a id="tweet_refresh" rel="nofollow" href="#" style="font-size: 70%">(refresh to see)</a>&nbsp;&#149;';
               $("#twitter_new_status").html(newstatus);
               $("#twitter_search_count").animate({ backgroundColor: "#fdb332"}, 1).animate({ backgroundColor: "#EEEEEE"}, 2000);
               $("a#tweet_refresh").click(function(e){
                  e.preventDefault();  
                  last_twitter_max_id = -1; // reset max id
                  last_twitter_refresh_url=''; // reset to force refetch without 'since' max id part
                  last_twitter_newcount = 0; // reset count to zero
                  $("#twitter_new_status").html('&nbsp;');
                  $("#numtweets").html(' (fetching...)');
                  twitterSearch();
                  if (!$("div#twitter_search_div").is('.open'))
                     $('div#twitter_search div.expand2').click();
                  return false;
               });
            }
            last_twitter_max_id = obj.max_id;
            last_twitter_refresh_url = obj.refresh_url;
         }  
         $("#twitter_search_count").css({ 'background-color': '#f5f3ef'});
         return;
      }
      last_twitter_max_id = obj.max_id;
      last_twitter_refresh_url = obj.refresh_url;

      var fetch_count = 0;
      $.each(obj.results, function(n,val){
         var title = val.text;
         var link = 'http://twitter.com/'+val.from_user+'/statuses/'+val.id;
         results += '<li><a class="tweet_content" title="view tweet details" rel="nofollow" href="'+link+'"><img class="screenshot2 tweet_profile_img" title="'+val.from_user+'" src="'+val.profile_image_url+'" alt="getting snapshot..." />&nbsp;'+title + '</a> <span class="tweet_time greyout"><nobr>'+val.howrecent+'</nobr></span></li>';
         fetch_count++;
         if (n >= 9)
            return false; // break out of .each() function
      });

      results += '</ul>';
      results += '<div style="text-align: center;margin: 0;"><img style="border-style:none;" src="img/powered-by-twitter-badge.gif" /></div>'

      if (fetch_count > 0)
         tweet_cnt_str = '  (Recent '+fetch_count+')';
      else
         tweet_cnt_str = '  (no tweets found)';

      $("#twitter_content").html(results);
      $("#numtweets").html(tweet_cnt_str);

      $("a.tweet_content").click(function(e){
         e.preventDefault();  
         var url=$(this).attr('href');
         var popwin = window.open(url, 'tweet_content_popup', 'toolbar=0, status=0, width=777, height=350');
         popwin.focus();
         return false;
      });

      screenshot2_init();
      $("#main_content").equalHeights(true);
   });
};

this.screenshot2_init = function(){
      $("img.screenshot2").hover(function(e){
                $("body").append("<p id='screenshot'><img src='"+ $(this).attr('src') +"' alt='getting snapshot...' width='48' height='48'/></p>");                                
                $("#screenshot")
                        .css("top",(e.pageY - 60) + "px")
                        .css("left",(e.pageX + 10) + "px")
                        .show();
        },
        function(){
                $("#screenshot").remove();
      });
      $("img.screenshot2").mousemove(function(e){
                $("#screenshot")
                        .css("top",(e.pageY - 60) + "px")
                        .css("left",(e.pageX + 10) + "px");
      });
};

function number_format (number, decimals, dec_point, thousands_sep) {
    var n = number, prec = decimals;

    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
};

this.other_results_ui_init = function(){
   if ($('#q-sm').length) {
      recentSearches.inProcess = false;
      twitterSearch.inProcess = false;
      recentSearches.cont_cnt = 0;
      twitterSearch.cont_cnt = 0;
      timer1Task.interval = 60000;
      timer2Task.interval = 60000;
      recentSearches.first = true;
      twitterSearch();
      recentSearches();
      timer1 = setTimeout('timer1Task()', 30000); // force initial twitter refetch to 30 secs for better user experience, 
                                                    // after that honor interval returned from ajax call
      timer2 = setTimeout('timer2Task()', 5000); // force initial recent searches refetch to 5 secs for better user experience, 
                                                  // after that honor interval returned from ajax call
      trending();
      screenshot2_init();
   }
}
