
var store = (function () {
  var useStorage = !!window.localStorage;
  
  return {
    get: function (key) {
      var value, ca, c, i;

      if (useStorage) {
        value = window.localStorage.getItem(key);
      } else {
        ca = document.cookie.split(';');
        for (i=0; i < ca.length; i++) {
          c = ca[i];
          while (c.charAt(0)==' ') {
            c = c.substring(1, c.length);
          }
          if (c && c.indexOf(key) == 0) {
            value = c.substring(key.length,c.length);
            break;
          }
        }
      }

      if (value == null) {
        value == "";
      }

      return value;
    },
    set: function (key, value) {
      if (useStorage) {
        try {
          window.localStorage.setItem(key, value);
        } catch (e) {
          // could be a QUOTA_EXCEEDED_ERR (for some reason Webkit is giving me this, just needs a restart and it goes away...)
        }
      } else {
        document.cookie = key + "=" + value + "; path=/";
      }      
    }
  };
})();

$('body').keyup(function (event) {
  if (event.which == 27) {
    clearTimeout(timer);
    //$('body').removeClass('auth').removeClass('loading');
    twitterlib.cancel();
  }
});

// very hacky code - sorry!
var $tweets = $('#tweets ul'), 
    screen_name = url = state = '', 
    page = 1, 
    pageMax = null,
    total_tweets = 0, 
    timer = null,
    total_searched = 0,
    statusTop = null, 
    type_string = { 
      timeline : 'tweets', 
      favs: 'favourites', 
      withfriends: 'friends&rsquo; tweets', 
      list: 'member tweets',
      dm: 'received direct messages',
      dm_sent: 'sent direct messages'
    };

twitterlib.cache(true);
twitterlib.custom('withfriends', '/proxy.php?page=%page%');
twitterlib.custom('dm', '/proxy.php?page=%page%&type=direct_messages');
twitterlib.custom('dm_sent', '/proxy.php?page=%page%&type=direct_messagesSent');
twitterlib.custom('mentions', '/proxy.php?page=%page%&type=statusesMentions');


$(function () {  
  var msie6 = $.browser == 'msie' && $.browser.version < 7;
  if (!msie6) {
    $(window).scroll(function (event) {
      var y;
      // what the y position of the scroll is
      if (statusTop != null) {
        y = $(this).scrollTop();

        // whether that's below the form
        if (y >= statusTop) {
          // if so, ad the fixed class
          $('#tweets aside').addClass('fixed');
        } else {
          // otherwise remove it
          $('#tweets aside').removeClass('fixed');
        }        
      }
    });
  }  
});

function updateLoading(text) {
  $('#loading').text(text);
}

//var $screen_name_label = $('#screen_name_label'),
//    $auth = $('#auth_screen_name'),
//    $screen_name = $('#screen_name');

function loadpage(qstr) {
  
  state = 'sdsd';
  
  var newstate = $(this).serialize(),
      type = 'timeline',
      search = '',
      filter = twitterlib.filter.format(search);

  //screen_name = 'sachagrimsditch';
  //screen_name = qstr.slice(1);
  screen_name = qstr;

  if (state != newstate) {
    state = newstate;
    store.set('screen_name', screen_name);
    
    //if (screen_name.match(/\//)) {
    //  type = 'list';
    //}

	
    total_tweets = 0;
    total_searched = 0;
	
    //updateLoading('loading ' + screen_name);

    $('#tweets ul').empty();
    
    //$('#permalink').attr('href', '/' + screen_name + '/' + type + '/' + encodeURIComponent(search));
    
    //$tweets.append('<li class="searchterm">Searching <em><strong>' + escapeTags(screen_name) + '</strong>&rsquo;s ' + type_string[type] + '</em> for <strong>' + escapeTags(search) + '</strong></li>');
    $('body').addClass('results');
    
    // cancel any outstanding request, and kick off a new one
    twitterlib.cancel()[type](screen_name, { filter: search, rts: true }, function (data, options) {
	
      total_searched += options.originalTweets.length;
      
      //setStatus(total_tweets + data.length, total_searched, options.originalTweets.length ? options.originalTweets[options.originalTweets.length - 1].created_at : null);
      
      // if there's no matched results, but there are raw Tweets, do another call - and keep going until we hit something
      if (data.length == 0 && total_tweets == 0 && options.originalTweets.length > 0) {
        // check if we're doing a page max
        updateLoading('press escape to cancel');
        clearTimeout(timer);
        timer = setTimeout(function () {
          twitterlib.next();
        }, 1000);          
        return;
      } else if (total_tweets > 0 && data.length == 0 && options.originalTweets.length > 0 && pageMax > 0) {
        pageMax--;
        updateLoading('press escape to cancel');
        clearTimeout(timer);
        timer = setTimeout(function () {
          twitterlib.next();
        }, 1000);
        return;
      }
      
                    
      var i = 0, j = 0, t, r, scrollPos = null, searches = filter.and.concat(filter.or).join('|');
      var ti = data.length;
	  if (ti >= 3) {ti = 3;}
	  
      //for (i = 0; i < data.length; i++) {
	  for (i = 0; i < ti; i++) {
        t = twitterlib.render(data[i], i);
		$('#tweets ul').append(t);
        
      }
      
      total_tweets += data.length;
      pageMax = null;
      
      updateLoading('');
	  
	  if (ti == 0) {
		$('#twitter').empty();
	  }
    });

  } else {
    updateLoading('press escape to cancel');
    clearTimeout(timer);
    timer = setTimeout(function () { twitterlib.cancel().next(); }, 250);
  } 
  
  
}

$('form').submit(function (e) {
  e.preventDefault();
  var qstr = $('#screenname').val();
  loadpage(qstr);
});



