function queryString(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split('&');
	for (var i=0; i<vars.length;i++) {
		var pair = vars[i].split('=');
    	if (pair[0] == variable) {
      		return pair[1];
    	}
  	}
	
	return 0;
}

function Ajax(url,options) {
  if (!(this instanceof Ajax)) return new Ajax(url, options);
  this.initialize(url,options);
};

Function.prototype.bind = function(obj) { 
	var method = this, 
	temp = function() { 
		return method.apply(obj, arguments); 
  	}; 
 
 	return temp; 
};

Ajax.prototype = {
	initialize: function(url, options){
		this.transport = this.getTransport();
		this.postBody = options.postBody || '';
		this.method = options.method || 'post';
		this.onLoad = options.onLoad || null;
		this.onComplete = options.onComplete || null;
		this.update = options.update || null;
		this.request(url);
	},

	request: function(url) {
		if (this.onLoad) {
			this.onLoad();
		}
		this.transport.open(this.method, url, true);
		this.transport.onreadystatechange = this.onStateChange.bind(this);
		if (this.method == 'post') {
			this.transport.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
			if (this.transport.overrideMimeType) this.transport.setRequestHeader('Connection', 'close');
		}
		this.transport.send(this.postBody);
	},

	onStateChange: function(){
		if (this.transport.readyState == 4) {
    		// if (this.transport.readyState == 4 && this.transport.status == 200) {
			if (this.onComplete) 			
				setTimeout(function(){this.onComplete(this.transport);}.bind(this), 10);
			if (this.update)
				setTimeout(function(){document.getElementById(this.update).innerHTML = this.transport.responseText;}.bind(this), 10);
			this.transport.onreadystatechange = function(){};
		}
	},

	getTransport: function() {
		http_request = false;
		
		if (window.XMLHttpRequest) { // Mozilla, Safari,...
	    	http_request = new XMLHttpRequest();
	     	if (http_request.overrideMimeType) {
	        	http_request.overrideMimeType('text/html');
	     	}	
	  	} else if (window.ActiveXObject) { // IE
	    	try {
	        	http_request = new ActiveXObject("Msxml2.XMLHTTP");
	     	} catch (e) {
	        	try {
	           		http_request = new ActiveXObject("Microsoft.XMLHTTP");
	        	} catch (e) {}
	     	}
		}
		
		return http_request;
	}
};

function showIndicator(indicator) {
	var top    = 'none';
	var bottom = 'none';
	var back   = 'none';
	
	if (typeof indicator != 'undefined') {
		if (indicator == 'bottom') {
			bottom = '';
		} else if (indicator == 'top') {
			top = '';
		} else {
			back = '';
		}
	}
	
	if (document.getElementById('loading_indicator_top')) {
		document.getElementById('loading_indicator_top').style.display = top;
	}
	
	if (document.getElementById('loading_indicator_bottom')) {
		document.getElementById('loading_indicator_bottom').style.display = bottom;
	}
	
	if (document.getElementById('loading_indicator_back')) {
		document.getElementById('loading_indicator_back').style.display = back;
	}
}

function showComments(response) {
	document.getElementById('results').innerHTML = response.responseText;
	//setTimeout(function() { document.getElementById('convo_body').scroll(0, 0); }, 10);
	
	showIndicator();
	
	if (document.getElementById('attention')) {
		if (previous_url != original_url) {
			document.getElementById('attention').style.display = '';
			document.getElementById('attention').innerHTML = '<a href="' + original_url + '" target="urlframe" onclick="loadComments(original_url, \'\', \'\', \'\', \'back\');return true;">Back to original conversation</a> <img src="/images/loading_indicator.gif" id="loading_indicator_back" style="display:none" />';
		} else {
			document.getElementById('attention').style.display = 'none';
		}
	}
}

function loadComments(location, source, page, all_sources, position) {
	location = decodeURIComponent(location);
	
	if (position == 'internal' && compareURLs(location, previous_url)) {
		return false;
	}
	
	previous_url = location;
	
	if (is_frame && document.getElementById('convo_close_button')) {
		document.getElementById('convo_close_button').href = location;
	}

	if (document.getElementById('convo_link_button')) {
		document.getElementById('convo_link_button').href = 'http://convotrack.com/' + location;
	} 
	
	new Ajax('http://convotrack.com/show/_comments/?url=' + encodeURIComponent(location) + (typeof source != 'undefined' ? '&src=' + source : '') + (typeof page != 'undefined' ? '&page=' + page : '') + (typeof all_sources != 'undefined' ? '&all_sources=' + all_sources : '') + (is_frame != 0 ? '&frame=1' : ''), {method:'get', onLoad:function() { showIndicator(position) }, onComplete:showComments});
	
	if (position == 'internal') {
		return true;
	} else {
		return false;
	}
}

function showLinkToConversation(response) {
	if (/^http/.test(response.responseText)) {
		alert(response.responseText);
	} else {
		alert('Incorrect ' + response.responseText);
	}
}

function loadLinkToConversation() {
	new Ajax('http://convotrack.com/shorten/_do/?url=' + encodeURIComponent(previous_url) + '&ajax=1', {method:'get', onLoad:function() { showIndicator() }, onComplete:showLinkToConversation});
	
	return false;
}

function loadFrame(location) {	
	if (compareURLs(location, original_url)) {
		return false;
	}
	
	top.location.href = 'http://convotrack.com/shorten/_do/?url=' + encodeURIComponent(original_url) + '&goto=' + encodeURIComponent(location);
	
	return false;
}

function compareURLs(first, second) {
	first  = decodeURIComponent(first);
	second = decodeURIComponent(second);
	
	first  = first.replace(/www\./gi, '');
	second = second.replace(/www\./gi, '');
	
	first  = first.replace(/\/$/, '');
	second = second.replace(/\/$/, '');
	
	return (first == second);
}

var is_frame     = decodeURIComponent(queryString('frame'));
var original_url = decodeURIComponent(queryString('url'));
var goto_url     = decodeURIComponent(queryString('goto_url'));
var previous_url = '';

if (goto_url != '0') {
	previous_url = original_url;
	window.onload = function() { loadComments(goto_url); }
} else {
	window.onload = function() { loadComments(original_url); }
}
