//	Tekdroid Ajax Functions
//	(c) S K Manji (skmanji {at} manji.org)

var ajax_object = null;

//	get the HTTP object
function get_ajax_object() {
	if (window.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP');
	else if (window.XMLHttpRequest) return new XMLHttpRequest();
	else {
		alert('Your browser does not support AJAX.');
		return null;
	}
}
 
//	get ajax url
function ajax_get(whichurl, whichtarget) {
	if (! whichtarget) { whichtarget='target'; }

	ajax_object = get_ajax_object();
	if (! ajax_object) { return; }

	ajax_object.onreadystatechange = function() {
		if(ajax_object.readyState == 4) { document.getElementById(whichtarget).innerHTML = ajax_object.responseText; }
	}

	ajax_object.open('GET', nocache_add(whichurl), true);
	ajax_object.send(null);
}

//	get input and get ajax url
function ajax_get_input(whichurl, text) {
	var myval = prompt(text, '');
	if (myval) { ajax_get(whichurl + myval); }
}

//	post url
function ajax_post(whichform, whichtarget) {
	if (! whichtarget) { whichtarget='target'; }

	ajax_object = get_ajax_object();
	if (! ajax_object) { return false; }

	ajax_object.onreadystatechange = function() {
		if(ajax_object.readyState == 4) { document.getElementById(whichtarget).innerHTML = ajax_object.responseText; }
	}

	var whichurl = whichform.action;

	//	create post data
	var data = 'file=' + whichurl + form_to_string(whichform);

	ajax_object.open('POST', nocache_add(whichurl), true);
	ajax_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	ajax_object.send(data);

	return false;
}

//	send screen size with ajax call
function ajax_get_size(whichurl) {
    var myWidth = 0, myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        myWidth = window.innerWidth; myHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth ||document.documentElement.clientHeight)) {
        myWidth = document.documentElement.clientWidth; myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        myWidth = document.body.clientWidth; myHeight = document.body.clientHeight;
    }
    ajax_get(whichurl+'?width='+myWidth+'&height='+myHeight);
}

//	add nocache to prevent browser caching
function nocache_add(whichurl) {
	var nocache = String((new Date()).getTime()).replace(/\D/gi,'');
	if (whichurl.indexOf('?') > 0) {
		return whichurl + '&nocache=' + nocache;
	}
	return whichurl + '?nocache=' + nocache;
}

//	convert form vars to postable string
function form_to_string(whichform) {
	var data = '';
	var elems = whichform.elements;
	var value = '';
	for(var i = 0; i < elems.length; i++) {
		if (elems[i].type=='checkbox') {
			if (elems[i].checked) { value = elems[i].value; }
			else { value = ''; }
		} else {
			var value = elems[i].value;
		}
		data += '&' + elems[i].name + '=' + value;
	}
	return data;
}
