/*
 * $Id$
 *
 * Basic javascript library for PhpWDS.
 */

phpwds_t= {
	msg_noconnection: "Gre\u0161ka u povezivanju sa serverom!"
}


function phpwdsHttpRequest (on_response) {
	this.xhr=null;

	var ths= this;

	function init() {
		if (window.XMLHttpRequest)
			ths.xhr= new XMLHttpRequest();
		else if (window.ActiveXObject)
			ths.xhr= new ActiveXObject('Microsoft.XMLHTTP');

		if (!ths.xhr) {
			data= new Object();
			data= phpwds_t.msg_noconnection;
			on_response(0, data);
		}
	}

	function onreadystatechange() {
		if (ths.xhr.readyState == 4) {
			var data= null;
			var ct= ths.xhr.getResponseHeader('Content-Type');
			if (ct.indexOf('text/plain')==-1 && ct.indexOf('application/json')==-1) {
				data= phpwds_t.msg_noconnection;
			} else {
				data= ths.xhr.responseText;
			}
			on_response(ths.xhr.status, data);
		}
	}

	function serializeData(data) {
		if (!data) return '';
		if (typeof(data) == 'string') return data;

		var str='';
		var delim='';

		var serialize= function(d, parent) {
			for(i in d) {
				if (typeof(d[i]) == 'object') {
					serialize(d[i], i);
				} else {
					var name= parent ? (parent + '[]') : i;
					str+= delim + name + '=' + encodeURIComponent(d[i]);
					delim= '&';
				}
			}
		}

		serialize(data);

		return str;
	}

	this.send= function(method, uri, data, accept, nocache) {
		if (!ths.xhr) return;
		var url= phpwds_baseurl;

		if (data && method=='GET')
			uri= uri + '?' + serializeData(data);

		ths.xhr.open(method, url + uri, true);
		//ths.xhr.setRequestHeader('Method', method + ' /' + uri + ' HTTP/1.1');
		if (method!='GET') ths.xhr.setRequestHeader('Cache-Control', 'no-cache');
		if (typeof(accept) != 'undefined') ths.xhr.setRequestHeader('Accept', accept);
		if (typeof(nocache) != 'undefined' && nocache) {
			//xhr.setRequestHeader('Pragma', 'no-cache');
			ths.xhr.setRequestHeader('Cache-Control', 'no-cache, must-revalidate');
		}
		ths.xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		ths.xhr.onreadystatechange= onreadystatechange;
		if (method=='GET')
			ths.xhr.send();
		else
			ths.xhr.send(serializeData(data));
	}

	init();
}

function phpwdsGetFormData(form_id) {
	var f= document.getElementById(form_id);
	var e= null;
	var tags = ['input', 'select', 'textarea'];
	var data= new Object();
	for (i in tags) {
		e= f.getElementsByTagName(tags[i]);
		for (j in e) {
			if (e[j].nodeType == 1 && e[j].name.length) {
				var tmp_data= null;
				var hasval= false;

				if (typeof(e[j].type) != "undefined" && (e[j].type == "checkbox" || e[j].type == "radio")) {
					if (e[j].checked) {
						tmp_data= e[j].value;
						hasval= true;
					}
				} else {
					tmp_data= e[j].value;
					hasval= true;
				}

				if (hasval) {
					if (e[j].name.substring(e[j].name.length-2, e[j].name.length) == '[]') {
						var name_a= e[j].name.substring(0, e[j].name.length-2);
						if (typeof(data[name_a]) == 'undefined')
							data[name_a]= new Array();
						data[name_a].push(tmp_data);
					} else {
						data[e[j].name]= tmp_data;
					}
				}
			}
		}
	}

	// Check for file upload iframe
	var file_upload_iframe= document.getElementById('file_upload_iframe');
	if (file_upload_iframe) {
		var doc = file_upload_iframe.contentDocument;
        if (doc == undefined || doc == null)
            doc = file_upload_iframe.contentWindow.document;
		e= doc.getElementById('file_upload_form').getElementsByTagName('input');
		data['_uploaded_files']= new Array();
		for (j in e) {
			if (typeof(e[j].type) != "undefined" && e[j].type == 'checkbox') {
				if (e[j].checked)
					data['_uploaded_files'].push(e[j].value);
			}
		}
	}

	return data;
}

function phpwdsShowSplash(msg, style, splash_id) {
	if (splash_id) phpwdsGetElementById(splash_id).innerHTML='<div class="splash_' + style + '">' + msg + '</div>';
}

function phpwdsGetElementById(id) {
	if (document.getElementById)
		return document.getElementById(id);
	else if (document.all)
		return document.all[id];
	return null;
}

/*
function phpwdsAsyncForm(method, uri, form_id, result_id, submit_msg, on_response, on_submit) {
	var x= new phpwdsHttpRequest(on_response);
	var f= phpwdsGetElementById(form_id);
	this.submitted= false;
	var ths= this;
	f.onsubmit= onSubmit;

	function onSubmit() {
		if (ths.submitted) return false;
		if (on_submit) on_submit();
		phpwdsGetElementById(result_id).innerHTML='<div class="ajax_loader">' + submit_msg + '</div>';
		ths.submitted= true;
		x.send(method, uri, phpwdsGetFormData(form_id), 'application/json, text/plain');
		return false;
	}
}
*/
function phpwdsAsyncForm(form_id, _uri, _method) {
	this.uri=_uri;
	this.method=_method;
	this.ctype='application/x-wwww-form-urlencoded';
	this.accept='text/plain';
	this.on_submit= null;
	this.on_response= null;
	this.nocache= false;

	var submitted= false;
	var xhr= null;
	var form= document.getElementById(form_id);
	var msg= null;
	var result_id= null;
	var ths= this;

	function onResponse(code, data) {
		if (ths.on_response)
			submitted= ths.on_response(code, data);
		else {
			submitted= false;
			if (code==200 || code==201) {
				phpwdsShowSplash(data, 'info', result_id);
				if (code==201) {
					submitted= true;
					var loc= xhr.xhr.getResponseHeader('Location');
					if (loc.indexOf('http')==-1) loc= phpwds_baseurl + loc;
					var t= setTimeout('window.location="' + loc + '"', 1000);
				}
				return;
			}
			phpwdsShowSplash(data, 'warn', result_id);
		}
	}

	function onSubmit() {
		if (submitted) return false;
		document.getElementById(result_id).innerHTML= '<div class="ajax_loader">' + msg + '</div>';
		if (ths.on_submit)
			ths.on_submit();
		submitted= true;
		xhr.send(ths.method, ths.uri, phpwdsGetFormData(form_id), ths.accept, ths.nocache);
		return false;
	}

	xhr= new phpwdsHttpRequest(onResponse);

	this.attach= function(_msg, _id) {
		form.onsubmit= onSubmit;
		msg= _msg;
		result_id= _id;
	}

	this.doSubmit= function() {
		onSubmit();
	}
}

function phpwdsLogout() {
	document.getElementById('logout_button_form').submit();
//	var xhr= new phpwdsHttpRequest(function(code, data) {
//		window.location= phpwds_baseurl;
//	});
//	xhr.send('POST', 'user/logout', null);
}

