// JavaScript Document

/*
	twitter.js - communicates with getTwitter.php to receive a twitter feed in json format and inserts relevant 'p' elements
*/



var Tweet = new Class({
	
	username : '', // holds username
	loaded : false, //set to true when data is loaded
	
	options : {
		url : 'http://www.hfs-clinics.co.uk/getTwitter.php', // url of php file
		limit : 3,
		container : 'ticker-inner',
		// EVENTS
		onSuccess : $empty,
		onFail : $empty
		
	},
	
	Implements: Events,
	
/*
	CONSTRUCTOR
	new Tweet(username:string|array[, options:object] ):object
		perfomrms xhr request for json file
		params:
			username : the twitter username
			options : the options object (see above)
*/
	
	initialize: function(username, options){
		this.setOptions(options);
		this.username = username;
		this.addConsole();
		var req = new Request.JSON({ url : this.options.url, onSuccess:this.success.bind(this), onFailure:this.fail.bind(this) });
		this.trace('id: ' +  username);
		req.get({ 'id' : username, 'format' : 'json', 'limit':this.options.limit });
	},
	
/*
	addConsole():void
		If debug is set to true, opens debuggin window
*/

	addConsole: function(){
		try{window.console.log();}catch(e){
			if( this.options.debug ){
				var console = {};
				console.win = window.open('', 'Debugger', 'width=250,height=500,scrollbars=1,resizable=1');
				console.win.document.write('<h2>Debugging Console</h2>');
				console.log = function(m){
					try{console.win.document.write(m + '<br />');}catch(e){}}
			}
		}
	},
		
	
/*
	trace(message:string):void
		outputs debugging info to console, or debugging window
*/
	trace: function(message){
		if(this.debug){console.log(message);}
	},

/*
	getDateString( datestamp:datestamp):string
		returns string formatted date from datestamp
*/
	
	getDateString: function(datestamp){
		var d = datestamp.split(' ');
		var date = d[2].toInt();
		var month = d[1];
		var year = d[5];
		switch(date){
			case 1 || 21 || 31 : date = date + 'st'; break;
			case 2 || 22 : date = date + 'nd'; break;
			case 3 || 23 : date = date + 'rd'; break;
			default : date = date + 'th'; break;
		}
		return date + ' ' + month + ' ' + year;
	},
	

/*
	fail( xhr:object ):void
		Fired if xhr request fails
*/
	
	fail: function(xhr){
		this.fireEvent('fail', [xhr]);
	},
/*
	success(objs:array, str:string):void
		Fired if xhr request succeeds
		Params:
			objs : the parsed json response, as array of objects
			str : the json response as a string
*/


/*
date = this.getDateString(obj[i].created_at)
text = obj[i].text
*/
	
	success: function(obj, str){
		var bas = [];
		var basicObj = {};
		for(i = 0; i < obj.length; i++){
			var basicObj = { 'date' : this.getDateString(obj[i].created_at), 'text' : obj[i].text, 'user' : obj[i].user.name};
			bas.push(basicObj);
			basicObj = {};}
		this.fireEvent('success', [bas, obj, str]);
	}
});

		
		
Tweet.implement(new Options);	
		