

var userName = 'shadowc_ar';
var format = 'json';
var interval = 180000;

var bind = function(func, obj/*, staticArg1, staticArg2... */) {
	// global and convenient bind function
	if (arguments.length > 2)
	{
		var staticArguments = [];
		for (var n=2; n < arguments.length; n++)
			staticArguments.push(arguments[n]);
		
		return function()
		{
			for (var i = 0; i < arguments.length; i++)
				staticArguments[staticArguments.length] = arguments[i];
			return func.apply(obj, staticArguments);
		};
	}
	else
	{
		return function()
		{
			return func.apply(obj, arguments);
		};
	}
};

twitterHelper = function() {
	this.httpRequest = null;
	this.since_id = null;
	this.targetId = 'tweetsUl';
	this.targetElem = null;
	
	// creating the httpRequest object
	if (window.XMLHttpRequest) {
		this.httpRequest = new XMLHttpRequest();
		if (this.httpRequest.overrideMimeType) {
			this.httpRequest.overrideMimeType('text/plain');
		}
	} else if (window.ActiveXObject) {
		try {
			this.httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				this.httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {}
		}
	}
	
	setTimeout(bind(this.getTweets, this), 500);
};

twitterHelper.prototype = {
	getTweets : function() {
		this.httpRequest.open('GET', '../js/twitterService.php?userName=' + userName + '&format=' + format + (this.since_id ? ('&since_id=' + this.since_id) : ''), true);
		this.httpRequest.onreadystatechange = bind(this.processTweets, this);			
		this.httpRequest.send();
	},
	
	processTweets : function() {
		
		if (this.httpRequest.readyState == 4) {
			if (this.httpRequest.status == 200) {
				var message = JSON.parse(this.httpRequest.responseText);
				var sinceIdChanged = false;
				
				if (!this.targetElem)
					this.targetElem = document.getElementById(this.targetId);
				
				
				if (message && message.length) {
					var temp = '';
					
					for (var n=0; n < message.length; n++) {
						
						if (!sinceIdChanged) {
							this.since_id = message[n].id;
							sinceIdChanged = true;
						}
						
						var links = message[n].text.match(/https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?/g);
						if (links) {
							links = this.sumarize(links);
							for (var a=0; a < links.length; a++)
								message[n].text = message[n].text.replace(links[a], ' <a href="' + links[a] + '" target="_blank">'+links[a]+'</a>');
						}
						
						var names = message[n].text.match(/\@([a-zA-Z0-9\-\_])+/g);
						if (names) {
							names = this.sumarize(names);
							for (var a=0; a < names.length; a++) 
								message[n].text = message[n].text.replace(names[a], '<a href="http://twitter.com/' + names[a].substr(1) + '" target="_blank">'+ names[a] + '</a>');
						}
						
						var searches = message[n].text.match(/\#([a-zA-Z0-9\-\_]+)/g);
						if (searches) {
							searches = this.sumarize(searches);
							for (var a=0; a < searches.length; a++)
								message[n].text = message[n].text.replace(searches[a], '<a href="http://twitter.com/search?q='+ searches[a] + '" target="_blank">'+searches[a]+'</a>');
						}
						
						temp += '<li>' + message[n].text + '<br /><span class="meta">Source ' + message[n].source;
						if (message[n].in_reply_to_status_id)
							temp += ' in reply to <a href="http://twitter.com/' + message[n].in_reply_to_screen_name + '/status/' + message[n].in_reply_to_status_id + '" target="_blank">' + message[n].in_reply_to_screen_name + '</a>';
							
						temp += '</span></li>';
						
					}
					
					this.targetElem.innerHTML = temp + this.targetElem.innerHTML;
					
				}
				
				setTimeout(bind(this.getTweets, this), interval);
			}
			else {
				//alert('Twitter update error ' + this.httpRequest.status);
			}
		}
	},
	
	// deletes duplicates in an array
	sumarize : function(a) {
		for (var n=0; n < a.length-1; n++) {
			for (var i=n+1; i < a.length; i++) {
				if (a[n] == a[i]) {
					a.splice(i,1);
					i--;
				}
			}
		}
		
		return a;
	}
};
 


var twitter = new twitterHelper();

// JSON implementation for unsupported browsers
if (!this.JSON) {
    this.JSON = {};
}

(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return isFinite(this.valueOf()) ?
                   this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z' : null;
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {
        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

            return String(value);

        case 'object':

            if (!value) {
                return 'null';
            }

            gap += indent;
            partial = [];

            if (Object.prototype.toString.apply(value) === '[object Array]') {
                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }
                v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {
                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

            v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

            var i;
            gap = '';
            indent = '';
            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }
            } else if (typeof space === 'string') {
                indent = space;
            }
            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }
            return str('', {'': value});
        };
    }

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

            var j;

            function walk(holder, key) {

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

                j = eval('(' + text + ')');
                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }
            throw new SyntaxError('JSON.parse');
        };
    }
}());

