// AJAX

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function makeRequest(requesttype, url, parameters, doafter) {
	
	http_request = false;

	if (window.XMLHttpRequest) { // Mozilla, Safari,...
	
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			// set type accordingly to anticipated content type
			//http_request.overrideMimeType('text/xml');
			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) {}
		}
	}
	
	if (!http_request) {
		alert('Cannot create XMLHTTP instance');
		return false;
	}
	
	http_request.onreadystatechange = function() {eval(doafter)};
	
	if(requesttype == 'GET'){
		totalurl = url + '?' + parameters;
		http_request.open('GET', totalurl, true);
		http_request.send('');
	} else {
		http_request.open('POST', url, true);
		http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http_request.setRequestHeader("Content-length", parameters.length);
		http_request.setRequestHeader("Connection", "close");
		http_request.send(parameters);
	}
	
}

function doNothing(){}

function reload_page(hr){
	if (hr.readyState == 4) {
		if (hr.status == 200) {
			window.location.reload(true);
		}
	}
}

// AJAX

function showDevice(deviceid){
	window.open("/equipment/device.cfm?id=" + deviceid, "Device", "resizeable=no,scrollbars=yes,height=345,width=650");
}

function invoice_preview(importid, agentid){
	document.getElementById('preview_area').innerHTML = "<iframe name=\"frame_processor\" id=\"frame_processor\" src=\"/invoice/creator/preview.cfm?import_id=" + importid + "&agentid=" + agentid + "\" style=\"width:100%;height:400;\" scrolling=\"auto\" frameborder=\"1\"></iframe>";	
}

function invoice_approve(importid, agentid){
	var params = "importid=" + importid + "&agentid=" + agentid;
	makeRequest('POST','/invoice/creator/approve.cfm', params, 'doNothing');
	document.getElementById(agentid).innerHTML='<img src="/images/chevron.small.png" hspace="8" align="absmiddle" /><a href="/invoice/" class="dash" target="viewer"><b>View Invoice</b></a>';
}

function invoice_discard(importid, agentid){
	var params = "importid=" + importid + "&agentid=" + agentid;
	makeRequest('POST','/invoice/creator/discard.cfm', params, 'doNothing');
	//document.getElementById(agentid).style.display='none';
	document.getElementById(agentid).innerHTML = '<b>Discarded</b>';
}