/*global function to get twitter user location */
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
var since = year + '-' + month + '-' + day;


var tweetUserObj = '';
var twitter_counter = 0; //prevent exceed the rate limit
twitter_request_limit = 4;
var effect_queue_interval = 500;
var tweetObj = '';
var since_id = '';
var default_keyword = 'reelclever';
var users = new Array();


function Search_Array(ArrayObj, SearchFor){
  var Found = false;
  for (var i = 0; i < ArrayObj.length; i++){
    if (ArrayObj[i] == SearchFor){
      return true;
      var Found = true;
      break;
    }
    else if ((i == (ArrayObj.length - 1)) && (!Found)){
      if (ArrayObj[i] != SearchFor){
        return false;
      }
    }
  }
}

function getLocation(username) {
  //
  if(twitter_counter < twitter_request_limit){
    twitter_counter = twitter_counter + 1;
		var url    = 'http://twitter.com/status/user_timeline/' + username + '.json?count=1&callback=getLocationCallback';
	  var pars   = '';
		var myAjax = new Ajax.XSRequest( url, {method: 'GET', parameters: pars} );
		if (  typeof(tweetUserObj)  != "undefined"  && tweetUserObj != '') {
		  if(tweetUserObj[0].user.location != ''){
        showAddress(tweetUserObj[0].user.location);
      }
    }
  }

}

var getLocationCallback = function (data){
      var rawdata = eval(data);
      if ( typeof( rawdata ) != "undefined" ) {
       //this is the url call back, we get new data
       tweetUserObj = rawdata;
     }
  }



function showAddress(address) {
  var geocoder = new GClientGeocoder();
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        //alert(address + " not found");
      } else {
        map.setCenter(point);
        var marker = new GMarker(point);
        map.addOverlay(marker);
        //marker.openInfoWindowHtml(address);
      }
    }
  );
}




var jsonCallback = function (data){
      var rawdata = eval(data);
if ( typeof( rawdata ) != "undefined" ) {
   //this is the url call back, we get new data
   tweetObj = rawdata;
   }

  }


function processJsonCallback(){

   since_id = '';
   var tweet = new Array();
  tweetObj.each(function(item, index) {
     tweet[index]=function(){};
     tweet[index].avatar = tweetObj[index].in_reply_to_user_id;
     tweet[index].id = tweetObj[index].in_reply_to_user_id;
     tweet[index].name = tweetObj[index].in_reply_to_screen_name;
     tweet[index].desc = tweetObj[index].text;
     var username = tweetObj[index].in_reply_to_screen_name;
     if( !Search_Array(users, username) ){
       users.push(username);// to ensure user will not be search twice
      // getLocation(username);
     }
	 if(since_id < tweetObj[index].id) { since_id =  tweetObj[index].id; }
  });
    tweet = tweet.reverse();
    /*
     * This if else condetion has been added to check whether the user has any tweet records or not
     * if "NO" then stop periodicalExecuter function and return false
     * if "YES" return array of teewts
     * */
    if((tweetObj.length)>0)
    {
    	$('twitter_loader').hide();
    	return tweet;
    }
    else
    {
    	var dd = new liveData();
    	dd.stopFunc();
    	return false;
    }
}

PeriodicalExecuter.prototype.registerCallback = function() {
	this.intervalID = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
}

PeriodicalExecuter.prototype.stop = function() {
	clearInterval(this.intervalID);
}


var liveData = Class.create();


liveData.prototype = {
	data: [{}],
	pe: 0,
	interval: 5,
	status: 1,
	throwErrors: false,
	initialize: function (keyword) {
		//this.fillHolder();
		//if(!this.keyword){this.keyword = default_keyword}
		this.pe = new PeriodicalExecuter(this.getNewData.bind(this), this.interval);
	},
	fillHolder: function () {
		$('twitter_streams').addClassName("streams");
		this.data.each(function(item, index) {
  		//var div = Builder.node('div', {className: 'hold'});
		  var tweetObj = document.createElement("li");
  		//var div = document.createElement("div");
			$('twitter_streams').insert({ top: tweetObj});
			tweetObj = $(tweetObj);
	  	//div.addClassName("hold");
			//div.innerHTML = '<img src="' + item.avatar +'">' + '<br /><a href="http://www.twitter.com/' + item.name + '">' + item.name + '</a><br />' + item.desc;
			//div.innerHTML = '<a href="http://www.twitter.com/' + item.name + '"> <img src="' + item.avatar +'" alt="'+item.name+'" width="37" height="37" /> </a> ' + '<div class="tweets"><a href="http://www.twitter.com/' + item.name + '">' + item.name + '</a>' + item.desc+'</div><div class="clr"></div>';
			//tweetObj.update('<a href="http://www.twitter.com/' + item.name + '" class="name">' + item.name + '</a>' + item.desc);
			tweetObj.update(item.desc.replace('@'+item.name, '<a href="http://www.twitter.com/' + item.name + '" class="name">@' + item.name + '</a>'));

			Element.hide(tweetObj, { queue: { position: 'end', scope: 'holders' } });
				new Effect.Appear(tweetObj, { queue: { position: 'end', scope: 'holders' } });
				new Effect.Highlight(tweetObj, { queue: { position: 'end', scope: 'holders' } });
		});
		Effect.Queues.get('holders').interval = effect_queue_interval;
	},
	getNewData: function () {
		//var showNewData = this.showNewData.bind(this);
		//var url = 'http://search.twitter.com/search.json?callback=jsonCallback&q='+keyword+'&rqq=1&lang=en&since='+since;
		//var url = 'http://search.twitter.com/search.json?callback=jsonCallback&q='+this.keyword+'&rqq=1&lang=en&rpp=4';
		var url = 'http://api.twitter.com/1/statuses/user_timeline.json?callback=jsonCallback&screen_name='+this.keyword+'&count=4';
		if(since_id){ url = url+'&since_id='+since_id}
		var pars   = '';
		if(since_id == "" || (since_id != "" && since_id != since_id))
		{
		  var myAjax = new Ajax.XSRequest( url, {method: 'GET',  requestHeaders: {Accept: 'application/json'}, parameters: pars /*onComplete: showNewData*/} )
		if (  typeof(tweetObj)  != "undefined" ) {
		  this.showNewData(processJsonCallback);
		}
	  }
	},
	showNewData: function (originalRequest) {	
		/*
		 * If tweets are found
		 * */		
		if((originalRequest().length)>0)
		{
			$('twitter_streams').innerHTML = "";
			for (var i = 0; i < originalRequest().length; i++){
				this.data.unshift(originalRequest()[i]);
				this.data.pop();
				this.fillHolder();
		    }
		}
		/* If No tweets found*/
		else
		{
			if(this.throwErrors)
			this.showMessage();
		}

	},
	playFunc: function () {
		if (this.status == 0) {
			this.pe = new PeriodicalExecuter(this.getNewData.bind(this), this.interval);
			this.status = 1;
		}
	},
	stopFunc: function () {
		this.pe.stop();
		this.status = 0;
	},
	showMessage: function (){
		var div = document.createElement("div");
		$('twitter_streams').innerHTML = "";
		$('twitter_streams').insert({ top: div});
		div = $(div);
  		div.innerHTML = "<div class='message'><span>No Tweets Found !!</span></div>";
	}
};
