var xhttpRequest;
var moving;
var initialXOffset;
var initialYOffset;
var initialSliderY;
var target;
var container;
var limitTop;
var limitBottom;
var dialString = "";
var lastDialString = "";
var oldDisplayData = new Array(3)
		oldDisplayData["1"] = "&nbsp;";
		oldDisplayData["2"] = "&nbsp;";
		oldDisplayData["3"] = "&nbsp;";

var displayTimer = new Array(3)
		displayTimer["1"] = "";
		displayTimer["2"] = "";
		displayTimer["3"] = "";

var micMsg;
var volMsg;
var phone;
var fetched;
var checkingPin;
var pin = "";
var phoneExtension=null;
var ringing=false;
var booth=false;
var autodial=false;
var hasAnswered = false;
var inbound =false;
var in_demo = false;
var demo_type = "";
var phoneRegistered = false;
var numberdialed = "";
var far, near, callingname;

var BLOCK_OUTGOING = true;

document.onmousemove = getMouseY;
document.onmouseup = mouseup;

function trim(str) {
	return ltrim(rtrim(str, " "), " ");
}

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"), "");
}

//This is called in main page to get the applet going
function startCorraleta(extension, enableBooth) {

	booth = enableBooth;
	phoneExtension = extension;

	/*alert("startCorraleta" + "|" + phoneExtension + "|" + booth);*/

/*	if (navigator.userAgent.toLowerCase().indexOf("msie") > -1) {
		document.write('<object id="faceless"');
		document.write(' classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"');
		document.write(' height="1" width="1"');
		document.write(' codebase="http://mexuar.com/pbx/phoneserv"');
		document.write(' hspace="0" vspace="0" align="middle">');
		document.write('<param name="code" value="Corraleta"/>');
		document.write('<param name="archive" value="Corraleta.jar"/>');
		document.write('<param name="mayscript" value="true"/>');
		document.write('<param name="debug" value="1"/>');
		document.write('</object>');
	} else {
		document.write('<object id="faceless"');
		document.write(' classid="java:Corraleta.class"');
		document.write(' type="application/x-java-applet"');
		if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) {
			document.write(' codebase="/pbx/phoneserv"');
		} else {
			document.write(' codebase="http://mexuar.com/pbx/phoneserv"');
		}
		document.write(' archive="Corraleta.jar"');
		document.write(' height="1" width="1"');
		document.write(' hspace="0" vspace="0" align="middle">');
		document.write('<param name="mayscript" value="true"/>');
		document.write('<param name="debug" value="1"/>');
		document.write('</object>');
	}
*/

}

function createParam(name, value)
{
	var param = document.createElement('param');
	param.setAttribute('name', name);
	param.setAttribute('value', value);
	
	return param;
}

//This is called in main page to get the applet going
function startCorraletaXHTML(extension, enableBooth) {

	booth = enableBooth;
	phoneExtension = extension;

}

//the applet calls in here early in the start up process
function setup() {

	if(phoneExtension != null) {
		show_status("Loading...");
	}

}

//the applet calls here once it is ready for use
function loaded() {
	
	/*alert("loaded()");*/

	//persist a handy variable for other functions
	//to use if they need to
	var phone = getPhone();
	
	phone.setCallingNumber(9100);
	phone.setCallingName("Web_User");
	phone.setUser("webuser");
	phone.setPass("webuser");
	phone.setWantIncoming(false);
	
	if(phoneExtension != null) {
		register();
	} else {
		phone.register();
	}

}

function register() {

	/*alert("register()");*/

	if(phoneExtension != null) {
		show_status("Registering...");
	}
	
	authenticated = false;
	checkingPin = false;

	if (booth) {

		/*alert("register(): Booth!");*/
		pinCheck();	

	} else {

		/*alert("register(): Authenticated mode");*/
		var url = "/phone/credentials/"+phoneExtension;
	
		xhttpRequest = XmlHttpRequestFactory(); 
	
		if (xhttpRequest == null ) {
			alert('Your browser does not support ajax!');
		} else {
			xhttpRequest.open("GET" , url , true);
			xhttpRequest.onreadystatechange = registerResponse;
			xhttpRequest.send(null);
			return; 	
		}	

	}

}

function registerResponse() {
	
	/*alert("registerResponse()" + "|" + pin + "|");*/

	if (booth) {

		var phone = getPhone();
		var password = pin;
		checkingPin = false;

		phone.setCallingNumber(phoneExtension);
		phone.setCallingName(phoneExtension);
		phone.setUser(phoneExtension);
		phone.setPass(password);
		if(in_demo) {
			phone.setWantIncoming(false);
		} else {
			phone.setWantIncoming(true);
		}
		phone.register();
		show_input("");

	} else {

		if (xhttpRequest.readyState == 4 && xhttpRequest.status == 200) { 
	
			var phone = getPhone();
			var password = trim(xhttpRequest.responseText);	
	
			phone.setCallingNumber(phoneExtension);
			phone.setCallingName(phoneExtension);
			phone.setUser(phoneExtension);
			phone.setPass(password);
			phone.setWantIncoming(true);
			phone.register();
	
		}

	}

}


function registered(status) {
	
	/*alert("registered()");*/
	/*alert("registered()" + "|" + status + "|");*/
	
	var statusCheck = status.substring(status.length - 14);
		
	if(! phoneRegistered) {

		if (statusCheck == "not registered") {
			/*alert("not registered() - not registered" + "|" + status + "|");*/
			if(phoneExtension != null) {
				show_status("Registration failed");
			}
			phoneRegistered = false;
			pinCheck();
		} else {
			/*alert("registered() - registered" + "|" + status + "|");*/
			if(phoneExtension != null) {
				show_status("Registered");
			}
			phoneRegistered = true;
		}	
		
	}

}


function findTop(obj) {
	var curtop = 0;
	var debug = "";
	if (obj.offsetParent) {
		do {
			curtop += obj.offsetTop;
			debug += obj.id + " - " + obj.offsetTop + "\n";
		} while (obj = obj.offsetParent);
	}
//	alert(debug);
	return curtop;
} 


function getMouseY(e) {

	// figure out if we're using IE or not
	var IE = document.all?true:false;

	// grab the Y coord of the mouse cursor
	if (IE) { 
		mouseY = event.clientY + document.body.scrollTop;
	} else {
		mouseY = e.pageY;
	}  

	// if the user has previously moused down on a control to move it
	if (moving) {

		var newY = mouseY + initialYOffset;

		if ( newY < limitTop ) { 
			newY = limitTop;
		}
		if ( newY > limitBottom ) {
			newY = limitBottom - target.offsetheight;
		}
		target.style.top = newY + "px";

		percent = 100 - ((newY - limitTop) * 2);
		if(percent < 0) {
			percent = 0;
		}
		if(percent > 100) {
			percent = 100;
		}
		percent += "%";
		if(percent == "NaN%") {
			percent = "0%";
		}

		phone_display(1,percent);

	}
}


function slider_mousedown(id, bounds) {
	moving = true;
	target = document.getElementById(id);
	container = document.getElementById(bounds);
	initialYOffset = target.offsetTop - mouseY;
	initialSliderY = target.offsetTop;
	limitTop = container.offsetTop;
	limitBottom = limitTop + 50;
	return false;
}


function mouseup() {
	moving = false;
	phone_display(1,"");
}


function phone_display_reset(line) {
	
	/*alert("phone_display_reset()");*/
	
	if(! checkingPin) {
		document.getElementById("phone-display-"+line).innerHTML = oldDisplayData[line];
		clearTimeout(displayTimer[line]);
		displayTimer[line] = null;
	}
}


function phone_display(line, message, timeout) {

	if(line == null || line < 1 || line > 3) {
		return;
	}

	if(timeout == null) {
		//set the display and don't revert it to it's previous state
		document.getElementById("phone-display-" + line).innerHTML = "&nbsp;" + message + "&nbsp;";
	} else {
		//set the display for a limited time only
		if(displayTimer[line] == null) {
			//save the existing message from the display so we can restore it when the timer runs out
			oldDisplayData[line] = document.getElementById("phone-display-" + line).innerHTML;
		} else {
			clearTimeout(displayTimer[line]);
		}
		displayTimer[line] = setTimeout("phone_display_reset(" + line + ")",timeout);
		document.getElementById("phone-display-" + line).innerHTML = "&nbsp;" + message + "&nbsp;";
	}
}

function show_status(message) {
	if(phoneExtension != null) {
		phone_display(1,message,2000);
	}
}

function show_progress(message,timeout) {
	phone_display(2,message,timeout);
}

function show_input(message) {
	phone_display(3,message);
}

function clear_display() {
	phone_display(1,"");
	phone_display(2,"");
	phone_display(3,"");
}

function buttonPush(key) {

	switch (key) {

		case "hangup":
			button_hangup();
		break;

		case "dial":
			if (ringing) {
				button_answer();
			} else {
				button_dial();
			}
		break;

		case "phone":
			button_mic();
		break;

		case "sound":
			button_vol();
		break;

		case "asterisk":
			button_digit("*");
		break;

		case "hash":
			button_digit("#");
		break;

		case "backspace":
			button_backspace();
		break;

		default:
			button_digit(key);
	
	}

}



function button_answer() {
	
	var phone = getPhone();
	phone.answer();
	ringing = false;

	if(phoneExtension != null) {
		show_status("Answered");
	}

}

function button_hangup() {
	var phone = getPhone();
	phone.hangup();
	ringing=false;


	if (checkingPin == 1) {
		dialString = "";
		pin = "";
		key = "";
		show_status("Enter pin:");
		show_input("");
	} else {
		dialString = "";
		show_input("");
	}
}

function button_dial() {
	/*alert("button_dial()");*/
	
	if (checkingPin == 1) {
		/*alert("button_dial(): checkingPin");*/
		registerResponse();
	} else {
		if(BLOCK_OUTGOING) {
			show_status("Calls Blocked");
			show_input("");
		} else {
			lastDialString = dialString;
			
			if(phoneExtension != null) {
				phone_dial(dialString);
			} else {
				dialString = "";	
			}
		}
	}
	dialString = "";
}

function button_mic() {
	if(micMsg == "Mic off") {
		micMsg = "Mic on";
	} else {
		micMsg = "Mic off";
	}
	
	if(phoneExtension != null) {
		show_status(micMsg);
	}
}

function button_vol() {
	if(volMsg == "Vol off") {
		volMsg = "Vol on";
	} else {
		volMsg = "Vol off";
	}
	
	if(phoneExtension != null) {
		show_status(volMsg);
	}
}

function button_digit(key) {
	if (checkingPin == 1) {
		dialString += "" + "*";
		pin += "" + key;
	} else {

		if(hasAnswered == true) {
			var phone = getPhone();
			phone.sendFirstCharDTMF(key);
			dialString += "" + key;
		} else {
			dialString += "" + key;
		}
	}
	
	if(phoneExtension != null) {
		show_input(dialString);
	}
}

function button_backspace() {
	dialString = substring(dialString,0,dialString.length-2);
	show_input(dialString);
}


//this updates the catalogue online/offline icon accordingly
function ajaxDial() {
	
	var url = "/phone/number/"+dialString;

	if (xmlhttp == null)
	{
		try{
			// Opera 8.0+, Firefox, Safari
			xmlhttp = new XMLHttpRequest();
		} catch (e){
			// Internet Explorer Browsers
			try{
				xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
			} catch (e) {
				try{
					xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
				} catch (e){
					// Something went wrong
					return false;
				} //try - catch
			} //try - catch
		} //try - catch
	}
	
	xmlhttp.open("GET", url, true);
	xmlhttp.onreadystatechange = function() { 
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
			var numberToDial = trim(xmlhttp.responseText);
			var phone = getPhone();

			if(phoneExtension != null) {
				show_status("Dialing: "+numberToDial);
			}

			phone.dial(numberToDial);
		} //if
	} //function
	    
	xmlhttp.send(null);
	    
} 


function browserversion() {

	var browser;
	if (navigator.userAgent.toLowerCase().indexOf("msie") > -1){
		browser = "ie";
	} else {
		browser = "other";
	}
	return browser;

}


function phone_dial(numberdialed) {

	var phone = getPhone();
	
	phone.dial(numberdialed);

}

function XmlHttpRequestFactory() {

	try {
		// Opera 8.0+, Firefox, Safari
		return (new XMLHttpRequest());
	} catch (e) {}

	try {
		// New IE
		return (new ActiveXObject('Msxml2.XMLHTTP2'));
	} catch (e) {}

	try {
		// Old IE
		return (new ActiveXObject('Microsoft.XMLHTTP'));
	} catch (e) {}

	return null;

}


function hostreachable(status, roundtrip) {
}


function newCall(inbound, far, near, answered, callingname) {
	
	if (inbound == "true") {
	
		// new incoming call
		ringing = true;
		show_progress("Incoming call...");
		show_input(far);

	} else {

		// new outbound call
		ringing = false;
		
		if(phoneExtension != null) {
			show_input(numberdialed);
			show_progress("Dialing...");
		}

	}

}


function hungUp(causecode) {

	lastDialString = dialString;
	clear_display();
	
	if(phoneExtension != null) {
		show_status("Hungup");
	}
	
	dialString = "";
	hasAnswered = false;

}


function ringing(inbound, far, near, answered, callingname) {
	if (!inbound) {
		if(phoneExtension != null) {
			show_progress("Ringing...");
		}
	}
}

function answered(inbound, far, near, answered, callingname) {
	if(phoneExtension != null) {
		show_progress("Answered");
	}
	hasAnswered = true;
}


function getPhone() {
	var phone = document.getElementById('faceless');
	return phone;
}


function setAudioCookie(name,val) {

  var nextyear = new Date();

  nextyear.setFullYear(nextyear.getFullYear() +1);
  setCookie(name,val,nextyear.toGMTString(),"/");

}


function setAudioInCookie(val) {

	setAudioCookie("inputDevice",val);

}


function setAudioOutCookie(val) {

	setAudioCookie("outputDevice",val);

}


function setCookie(name, value, expires, path, domain, secure) {

	var cook = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
	document.cookie = cook;

}


function getCookie(name) {

	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) {
			return null;
		}
	} else {
		begin += 2;
	}
	
	var end = document.cookie.indexOf(";", begin);
	
	if (end == -1) {
		end = dc.length;
	}

	return unescape(dc.substring(begin + prefix.length, end));

}


function deleteCookie(name, path, domain) {

    if (getCookie(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }

}


function pinCheck() {

	/*alert("pinCheck()");*/
	
	pin = "";

	checkingPin = 1;
	
	if(phoneExtension != null) {
		show_status("Enter pin:");
	}

}


function rollover(btn) {

	var imgName = "button-"+btn;
	var imgObj = document.getElementById(imgName);

	imgObj.src = "/sites/all/modules/mexuar/phone/images/button-" + btn + "-hover.png";

}

function rollout(btn) {

	var imgName = "button-"+btn;
	var imgObj = document.getElementById(imgName);

	imgObj.src = "/sites/all/modules/mexuar/phone/images/button-" + btn + ".png";

}


function demo_call() {

	phone_dial(9100);
	
}


function demo_conference() {

	phone_dial(9200);
	
}