		
// utility function for escaping html
function escape(html) {
	return html.
		replace(/&/gmi, '&amp;').
		replace(/"/gmi, '&quot;').
		replace(/>/gmi, '&gt;').
		replace(/</gmi, '&lt;');
}

function strip(html){
	return html.
		replace(/&/gmi, '').
		replace(/"/gmi, '').
		replace(/>/gmi, '').
		replace(/</gmi, '');	
}

//	Delay function for jquery.
//	Usage: $(this).delay(3000); 

$.fn.delay = function(time, callback){
    // Empty function:
    jQuery.fx.step.delay = function(){};
    // Return meaningless animation, (will be added to queue)
    return this.animate({delay:1}, time, callback);
};

function getNewConnection () {
	
	if (CONNECTION === null ){

		// connect to the sever
		CONNECTION = new Strophe.Connection(BOSH_SERVICE);
		// get a random jid  
		CONNECTION.connect('anon.frontdesk.im','', onConnect);
		// Add handlers connection.addHandler(callback, namespace, stanza_name, type, id, from) 
		CONNECTION.addHandler(handleQueueInfo, null, 'iq', 'set', null, null);
		CONNECTION.addHandler(handleMessage, null, 'message', null, null, null);
	}
	
}

function onConnect(status) {

    //change the msg and icon
	$('#status-msg').text("Connecting ...");
	$('#status-icon').addClass("connecting");
    
    //check to see how the connection went
	if (status == Strophe.Status.CONNFAIL) {
    
		setConnectFail();
		getNewConnection();    
    
    } else if ( status == Strophe.Status.DISCONNECTED ) {
    
		if ( CHAT_STATE === null | CHAT_STATE == 'new'){
			setChatUnavailable();
			CHAT_STATE = 'unavailable';
			$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
			$.cookie('frontdesk', null, COOKIE_OPTIONS);
			//console.log('chat state: '+CHAT_STATE);	
		}else{
			setChatDisconnect();
		}
		getNewConnection();
    
	} else if (status == Strophe.Status.CONNECTED) {
	
		if ( $.cookie('frontdesk') !== null ) {
		
			FDID = $.cookie('frontdesk');

			// build iq request
			var id = CONNECTION.getUniqueId('getFrontDeskIdConnect');
			var FDIDiq = $iq({
			'from': CONNECTION.jid + "/" + CONNECTION.resource,
			'to': COMPONENT,
			'id': id,
			'type': 'get'
				}).c('query', {
						'xmlns': FDINIT,
						'frontdeskid': FDID
			});
			// Add handlers connection.addHandler(callback, namespace, stanza_name, type, id, from) 
			CONNECTION.addHandler(handleRequestStatus, null, 'iq', null, id, null);
			CONNECTION.addHandler(handleStatusError, null, 'iq', 'error', id, null);
			CONNECTION.send(FDIDiq.tree());	
			//console.log("send from onConnect: " + FDIDiq.tree());		
		}
		requestQstatus("onConnect");
	}
}

function requestQstatus(sentFrom) {
        // request to check status of queue
		var id = CONNECTION.getUniqueId('requestQstatus_'+sentFrom);
		var checkQstatIQ = $iq({
			'to': QUEUE,
			'type': 'get',
			'id': id
		}).c('query', {
			'xmlns': FDQUEUE + '_stats'
			});
		// Add Strophe handlers connection.addHandler(callback, namespace, stanza_name, type, id, from)
		CONNECTION.addHandler(handleQstatus, null, 'iq', null, id, null);
		CONNECTION.addHandler(handleQstatusErr, null, 'iq', 'error', id, null);
		CONNECTION.send(checkQstatIQ.tree());
        
		var presQ = $pres({'to': QUEUE });
		CONNECTION.addHandler(handlePresence, null, 'presence', null, null, null);
		CONNECTION.send(presQ.tree());
}

function handleQueueInfo(iq) {
	var servicers = $(iq).find('query').map(function () {  
							return $(this).attr("servicers");  
						}).get();
    var available = $(iq).find('query').map(function () {   
							return $(this).attr("available");  
						}).get();
	var size = $(iq).find('query').map(function () {
							return $(this).attr("size");  
						}).get();
	var next = '';
	var currently = '';
	var peeps = '';
	var isWaiting = '';
	var ahead = '';
	var reps = '';
	var isRep = 'is';
	var printSize = '';
	var printServicers = '';
    
    if ( size === 0 ){
		next = "You're next in line";
		size = '';
		printSize = 'and';
	}
	else if ( size == 1 ){
		currently = "Currently,";
		peeps = "person";
		isWaiting = "is";
		size = "one";
		ahead = ' waiting ahead of you and ';
	}
	else if ( size > 1  && size <=10  ){
		currently = "Currently,";
		peeps = "people";
		isWaiting = "are";
		ahead = ' waiting ahead of you and ';		
		printSize = size;
		size += '';
		size = '';
	}
	else {
		currently = "Currently,";
		peeps = "people";
		isWaiting = "are";
		ahead = ' waiting ahead of you and ';
	}
	if ( servicers > 1 ) {
		reps = reps + "s";
		isRep = "are";
	}
	if ( servicers <= 10 ){
		var i = servicers;
		printServicers = servicers;
		servicers += '';
		servicers = '';
	}
	if ( available == 'True' ){
		var html = '';
		//html += '<p class="wait-status">' + next + currently + ' ' + printSize + size + ' ' + peeps + ' ' + isWaiting + ahead + printServicers + servicers + ' representative' + reps + ' ' + isRep + ' serving the queue. Thanks very much for your patience.</p>';
		html = '<p class="wait-status">Thanks very much for your patience.</p>';
		setChatWaiting();
		CHAT_STATE = 'waiting';
		$.cookie( 'frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
		//console.log( 'chat state: '+CHAT_STATE );
		updateChatHistory(html);  
	}else {
		if ( CHAT_STATE === null | CHAT_STATE == 'new' ){
			setChatUnavailable();
			CHAT_STATE = 'unavailable';
			$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
			$.cookie('frontdesk', null, COOKIE_OPTIONS);
			//console.log('chat state: '+CHAT_STATE);	
		}
		else{
			setChatDisconnect();
		}
	}
}
	
function handleRequestStatus(iq) {
	var chats = $(iq).find('query').map(function () {  
		return $(this).attr("chats");  
	}).get();
	var queues = $(iq).find('query').map(function () {  
		return $(this).attr("queues");  
	}).get();
	INCID = $(iq).find('query').map(function () {  
						return $(this).attr("inc_id");  
     				}).get(); 	
	NICKNAME = $(iq).find('query').map(function () {
		return $(this).attr("nick");
	}).get();
	if ( queues == 1 ){
		setChatWaiting();
		CHAT_STATE = 'waiting';
		$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
		//console.log('chat state: '+CHAT_STATE);
		joinQueue(FDID); 
	}else if ( chats == 1 ){
		clearChatHistory();
		setChatting();
		CHAT_STATE = 'chatting';
		$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
		//console.log('chat state: '+CHAT_STATE);
	}
	//reset the cookie
	$.cookie('frontdesk', FDID, COOKIE_OPTIONS);
}


function handleStatusError(error) {
	getNewConnection();
	setChatUnavailable();
	CHAT_STATE = 'unavailable';
	$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
	$.cookie('frontdesk', null, COOKIE_OPTIONS);
	//console.log('chat state: '+CHAT_STATE);	
}

function handleMessage(msg) {
	var body = '';
	var namespace = "http://jabber.org/protocol/muc#user";
	var from = $(msg).attr("from");
	var printFrom = "";
	var start = from.indexOf("/") + 1;
	var end = from.indexOf("_");
	if (end == -1){end = from.length;}
	var me2 = ME.slice(start, end);
	printFrom = from.slice(start, end);
	if (me2 == printFrom ){
		printFrom = "Me";
	}else{
		printFrom = from.slice(start, end);
	}
	var type = msg.getAttribute("type");
    $(msg).find('x').each(function (index) {
		if ( this.namespaceURI == namespace ){
			if ( this.hasChildNodes() ){   		
				sendPresChat(from);
				//console.log("sendPresChat:" + from);
			}
		}
	});
    
	if ( type  == 'groupchat' || type == 'chat' ) {
		body = Strophe.getText(msg.getElementsByTagName('body')[0]);
	//	body = escape(body);
					 
		var html = '';
		html += '<p>';
		if (printFrom == "Me") {
			html += '<span class="chatusername">';
			html += printFrom;
			html += ':</span> ';
			html += body + '</p>';
		}else if (printFrom == "FrontDesk") {
			html +='<span class="server">Now chatting with representative</>';
		}else {
			html += '<span class="chatservicername">';
			html += printFrom;
			html += ':</span> ';
			html += body + '</p>';
		}
	if ( from.indexOf("/") != -1)
		updateChatHistory(html);
	}
	return true;
}

function sendPresChat(from) {
	page = document.location.href;
	var toChat = from + "/" + NICKNAME + "_" + INCID ;
	ME = toChat;
	//console.log("ME: " + ME);
	var id = CONNECTION.getUniqueId('presChat');
	var presChat = $pres({'to': toChat, 'id': id }).c('status').t(page);
	CONNECTION.send(presChat.tree());
	//console.log("from sendPresChat: " + presChat.tree());
	ROOM = from;
	setChatting();
	CHAT_STATE = 'chatting';
	$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
	//console.log('chat state: '+CHAT_STATE);
	maxChatWin();
}

function handlePresence (pres) {
	//console.log("entire pres:" + pres);
	var from = pres.getAttribute('from');
	var type = pres.getAttribute('type');
	//console.log("Handle Presence from: " + from);
	//console.log("handle presence me: " + ME);
	//console.log("handle presence room: " + ROOM);
	//console.log("Handle Presence type: " + type);
	if ( from == COMPONENT+'/manager' && CHAT_STATE != 'new' ) {
		setChatDisconnect();
		CHAT_STATE = 'disconnect';
		$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
		$.cookie('frontdesk', null, COOKIE_OPTIONS);
		//console.log('chat state: '+CHAT_STATE);
	    	
	}else if ( from == ME && type == 'unavailable' ){
	// add uiBlock for chatting
		setChatEnded();
		CHAT_STATE = 'ended';
		$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
		$.cookie('frontdesk', null, COOKIE_OPTIONS);
		//console.log('chat state: '+CHAT_STATE);
	}
	var namespace = FDQUEUE + "_stats";
	$(pres).find('x').each(function () {
		if ( this.namespaceURI == namespace ){
			var servicers = $(pres).find('x').map(function () {  
							return $(this).attr("servicers");  
						}).get();
			var available = $(pres).find('x').map(function () {   
							return $(this).attr("available");  
						}).get();
			var size = ($(pres).find('x').map(function () {
							return $(this).attr("size");  
						}).get());
			//console.log('servicers: '+servicers+' : available: '+available+' : size: '+size);
							
			var next = '';
			var currently = '';
			var peeps = '';
			var isWaiting = '';
			var ahead = '';
			var reps = '';
			var isRep = 'is';
			var printSize = '';
			var printServicers = '';
    
		    if (size === 0){
				next = "You're next in line";
				size = '';
				printSize = 'and';
			}
			else if (size == 1){
				currently = "Currently,";
				peeps = "person";
				isWaiting = "is";
				size = "one";
				ahead = ' waiting ahead of you and ';
			}
			else if (size > 1  && size <=10  ){
				currently = "Currently,";
				peeps = "people";
				isWaiting = "are";
				ahead = ' waiting ahead of you and ';		
				printSize = size;
				size += '';
				size = '';		   	
			}
			else {
				currently = "Currently,";
				peeps = "people";
				isWaiting = "are";
				ahead = ' waiting ahead of you and ';
			}
			
			if (servicers > 1) {
				reps = reps + "s";
				isRep = "are";
			}
			
			if (servicers <= 10){
				var i = servicers;
				printServicers = servicers;
				servicers += '';
				servicers = '';
			}
			
			if (available == 'True' && CHAT_STATE == 'waiting'){
				//console.log('available True and chat state waiting');
				var html = '';
				//html += '<p class="wait-status">' + next + currently + ' ' + printSize + size + ' ' + peeps + ' ' + isWaiting + ahead + printServicers + servicers + ' representative' + reps + ' ' + isRep + ' serving the queue. Thanks very much for your patience.</p>';
				html = '<p class="wait-status">Thanks very much for your patience.</p>'
				clearChatHistory();
				updateChatHistory(html);
				CHAT_STATE = 'waiting';
				$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
		//console.log('chat state: '+CHAT_STATE);
			}else if ( available == 'True' && CHAT_STATE == 'ended' ) {
				//console.log('available True and chat state ended');
				//console.log('CHAT_STATE: '+CHAT_STATE);
				setChatAvailable();
				//setChatUnavailable();
				CHAT_STATE = 'available';
				$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
		//console.log('chat state: '+CHAT_STATE);
			}else if ( available == 'True' && CHAT_STATE == 'disconnect' ) {
				//console.log('available True and chat state disconnect');
				//console.log('CHAT_STATE: '+CHAT_STATE);
				setChatAvailable();
				//setChatUnavailable();
				CHAT_STATE = 'available';
				$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
		//console.log('chat state: '+CHAT_STATE);
			}else if ( available == 'True' && CHAT_STATE == 'unavailable' ) {
				//console.log('available True and chat state unavailable');
				//console.log('CHAT_STATE: '+CHAT_STATE);
				setChatAvailable();
				//setChatUnavailable();
				CHAT_STATE = 'available';
				$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
		//console.log('chat state: '+CHAT_STATE);
			}else if ( available == 'False' && CHAT_STATE == 'new' ) {
				//console.log('available false and chat state not new');
				//console.log('CHAT_STATE: '+CHAT_STATE);
				setChatUnavailable();
				CHAT_STATE = 'unavailable';
				$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
				$.cookie('frontdesk', null, COOKIE_OPTIONS);
		//console.log('chat state: '+CHAT_STATE);
			}else if ( available == 'False' && CHAT_STATE == 'waiting' ) {
				//console.log('available false and chat state not new');
				//console.log('CHAT_STATE: '+CHAT_STATE);
				setChatDisconnect();
				CHAT_STATE = 'disconnect';
				$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
				$.cookie('frontdesk', null, COOKIE_OPTIONS);
		//console.log('chat state: '+CHAT_STATE);
			}else if ( available == 'False' && CHAT_STATE == 'chatting' ) {
				//console.log('available false and chat state not new');
				//console.log('CHAT_STATE: '+CHAT_STATE);
				setChatDisconnect();
				CHAT_STATE = 'disconnect';
				$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
				$.cookie('frontdesk', null, COOKIE_OPTIONS);
		//console.log('chat state: '+CHAT_STATE);
			}else if ( available == 'False' && CHAT_STATE == 'ended' ) {
				//console.log('available false and chat state not new');
				//console.log('CHAT_STATE: '+CHAT_STATE);
				setChatUnavailable();
				CHAT_STATE = 'unavailable';
				$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
				$.cookie('frontdesk', null, COOKIE_OPTIONS);
		//console.log('chat state: '+CHAT_STATE);
			}else if ( available == 'False' && CHAT_STATE == 'disconnect' ) {
				//console.log('available false and chat state not new');
				//console.log('CHAT_STATE: '+CHAT_STATE);
				setChatUnavailable();
				CHAT_STATE = 'unavailable';
				$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
				$.cookie('frontdesk', null, COOKIE_OPTIONS);
		//console.log('chat state: '+CHAT_STATE);
			}else if ( available == 'False' && CHAT_STATE == 'unavailable' ) {
				//console.log('available false and chat state not new');
				//console.log('CHAT_STATE: '+CHAT_STATE);
				setChatUnavailable();
				CHAT_STATE = 'unavailable';
				$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
				$.cookie('frontdesk', null, COOKIE_OPTIONS);
		//console.log('chat state: '+CHAT_STATE);
			}else if ( available == 'True' && CHAT_STATE == 'new'){
				//console.log('available True and chat state new')
				setChatAvailable();
				//setChatUnavailable();
			
				$("#chatbubble").delay(1000).animate({'marginTop' : '-=10', 'opacity' : 'show'}, "fast",
					function(){ 
						$(this).delay(3000); 
						$(this).animate({'marginTop' : '+=10', 'opacity' : 'hide'}, 'hide');
					});
					CHAT_STATE = 'available';
					$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
				//console.log('chat state: '+CHAT_STATE);	
			}
			
	}});
	return true;
}

function handlePresUnavailable (pres) {
	var from = pres.getAttribute('from');


	//console.log("from: " + from);
	//console.log("type: " + type);
	//console.log("from build: " + ROOM + '/' + NICKNAME + '_' + INCID );
	//console.log("COMPONENT: " + COMPONENT);


}
          
function handleQstatus(iq) {

	var type = iq.getAttribute('type');
	var servicers = $(iq).find('query').map(function () {  
		return $(this).attr("servicers");  
	}).get(); 
	if (type == 'result' &&  servicers > 0 && FDID == '' ) {
		setChatAvailable();
		//setChatUnavailable();
		soundManager.play('keyshake-sound');
	}
	else if (FDID != ''){
	}	
	else {
		setChatUnavailable();
		CHAT_STATE = 'unavailable';
		$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
		$.cookie('frontdesk', null, COOKIE_OPTIONS);
		//console.log('chat state: '+CHAT_STATE);	
	}
	return false;

}

function handleQstatusErr(){
	setChatUnavailable();
	CHAT_STATE = 'unavailable';
	$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
	$.cookie('frontdesk', null, COOKIE_OPTIONS);
	//console.log('chat state: '+CHAT_STATE);	
}

function handleQstatusChatEnd(iq) {
	var type = iq.getAttribute('type');
	var servicers = $(iq).find('query').map(function () {  
		return $(this).attr("servicers");  
	}).get(); 
	if (type == 'result' &&  servicers > 0 ) {
		setChatAvailable();
		//setChatUnavailable();
	}	
	else {
		setStatusUnavailable();
	}
	return false;
}

function joinQueue(FDID) {

    // build request to join queue
	var id = CONNECTION.getUniqueId('joinqueue');
	var joinqueueiq = $iq({'from':CONNECTION.jid+"/"+CONNECTION.resource,
				'to': QUEUE,
				'id':id,
				'type':'get'})
    				.c('query', {
    					'xmlns': FDQUEUE, 
    					'nick': NICKNAME })
    						.t(REQUESTMSG);
	
	// add handlers for callback
	CONNECTION.addHandler(handleJoinQueue, null, 'iq', null, id, null);
	CONNECTION.send(joinqueueiq.tree());
	//console.log("from joinQueue: " + joinqueueiq.tree()); 
	setChatWaiting();
	CHAT_STATE = 'waiting';
	$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
	//console.log('chat state: '+CHAT_STATE);
 }

function handleJoinQueue(iq) {
	var type = iq.getAttribute('type');
	if (type == 'result'){
		var html = '';
		html += "<p class='welcome-msg'>A representative will be with you momentarily.</p>";
		updateChatHistory(html);
	}else{
		setChatDisconnect();
	} 
	return false;
}

function validate_required(field,alerttxt)
{
with (field)
  {
  if (value==null||value=="")
    {
    alert(alerttxt);return false;
    }
  else
    {
    return true;
    }
  }
}
function submitRequestForm(requestform){
	//console.log("submit request form clicked");
	with(requestform){
		if (validate_required(nickname,"No really. I need your name. Make one up if you'd like.")==false){
			nickname.focus();
			return false;
		}
		if (validate_required(how,"It would really help me out if I knew what this was about. I don't need a bunch of detail, but at least a single word topic would be nice.")==false){
			how.focus();
			return false;
		}
	}
	NICKNAME = requestform.nickname.value;
	REQUESTMSG = requestform.how.value;
	getFrontdeskid();
}

function getFrontdeskid(requestform) {
	var id = CONNECTION.getUniqueId('getFrontdeskid');
	var getFDIDiq = $iq({'from':CONNECTION.jid+"/"+CONNECTION.resource,
					'to': COMPONENT,
					'id': id,
					'type':'get'}
		)
		.c('query', {'xmlns': FDINIT, 'nick': NICKNAME});
	CONNECTION.addHandler(handleGetFDID, null, 'iq', null, id, null);
	CONNECTION.send(getFDIDiq.tree());
	//console.log("from getFrontdeskid: " + getFDIDiq.tree());
	$('.title-status').text('Sending your request...'); 
	setChatWaiting();
	CHAT_STATE = 'waiting';
	$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
	//console.log('chat state: '+CHAT_STATE);	 
}

function handleGetFDID(iq){
	var type = iq.getAttribute('type');
	if (type == 'result'){
		var chats = $(iq).find('query').map(function () {  
         	return $(this).attr("chats");  
     	}).get();
     	var queues = $(iq).find('query').map(function () {  
         	return $(this).attr("queues");  
     	}).get();
		FDID = $(iq).find('query').map(function () {  
         	return $(this).attr("frontdeskid");  
     	}).get();
		INCID = $(iq).find('query').map(function () {  
			return $(this).attr('inc_id');  
		}).get();
		//console.log("chats: " + chats);
		//console.log("queues: " + queues);
		//console.log("FDID: " + FDID);
		//console.log("INCID: " + INCID);
		if ( queues == 1 ){
			setChatWaiting();
			CHAT_STATE = 'waiting';
			$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
			//console.log('chat state: '+CHAT_STATE); 
		}
		if ( chats == 1 ){
			setChatting();
			CHAT_STATE = 'chatting';
			$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
			//console.log('chat state: '+CHAT_STATE);
		}
		joinQueue(FDID);  	
		$.cookie('frontdesk', FDID, COOKIE_OPTIONS); 
	}else if ( CHAT_STATE != 'failed_fdid'){
		setChatDisconnect();
		CHAT_STATE = 'failed_fdid';
		$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
		$.cookie('frontdesk', null, COOKIE_OPTIONS);
		//console.log('chat state: '+CHAT_STATE);
		getFrontdeskid();
	}else {
		setChatDisconnect();	
	}
	return false;
}

function sendMessage(chatForm) {

	if (chatForm.text.value) {
		message = $msg({
			'type': 'groupchat',
            'to': ROOM
        }).c('body').t(chatForm.text.value);
			CONNECTION.send(message.tree());
			//console.log("from sendMessage:" +message.tree() );
			chatForm.text.value = '';
	}
	return true;
}

function endChat() {
	
	//console.log("user ended chat function endChat");
	
	//destroy cookie
	$.cookie('frontdesk', null, COOKIE_OPTIONS);
	
	if ( CHAT_STATE == 'chatting' || CHAT_STATE == 'waiting'){
		//send presence unvailable to chatroom 
		var id = CONNECTION.getUniqueId('presChat');
		var presChat = $pres({'to': ME, 'id': id, 'type':'unavailable' });
		CONNECTION.send(presChat.tree());
		//console.log("from endChat:" + presChat.tree());
		id = CONNECTION.getUniqueId('leaveQueue');
		var leavequeueiq = $iq({'from':CONNECTION.jid+"/"+CONNECTION.resource,
					'to': QUEUE,
					'id':id,
					'type':'get'})
	    				.c('query', {
	    					'xmlns': FDQUEUE + '_leave', 
	    					'nick': NICKNAME });
	    CONNECTION.send(leavequeueiq.tree());
	    //console.log("from endChat: " +leavequeueiq.tree());
    }
    
	//clear the chat window
	clearChat();
	setChatEnded();
	CHAT_STATE = 'ended';
	$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
	$.cookie('frontdesk', null, COOKIE_OPTIONS);
	//console.log('chat state: '+CHAT_STATE);	
}

// functions for display window settings

function updateChatHistory(html) { 
	$('#chathistory').append(html);
	$('#chathistory').attr({ scrollTop: $('#chathistory').attr('scrollHeight') });

	if (( WIN_STATE == "min" || DOC_FOCUS === false ) && ( CHAT_STATE == 'chatting' )) {
		soundManager.play('piano2-sound');
		$('#status-msg').text('New message');
		var i=0;
		var doc_title = document.title;
		while (i<=3){
			$('#status-msg').animate({'color' : '#46a51b'}, 500).animate({'color' : '#000000'}, 500);
			i++;
  		}
	}
}

function clearChatHistory(){
//console.log('clearChatHistory');
	$('#chathistory').empty();
}

function minChatWin() {
//console.log('minChatWin');
	$('#chatbox, #titlebar, #popout-btn').hide();
	$('#maximize').show();
	WIN_STATE = 'min';
	$('#status-msg').bind('click',function() { maxChatWin(); return false; });

}

function maxChatWin() { 
//console.log('maxChatWin');
	$('#chatbox, #titlebar, #popout-btn').show();
	$('#maximize, #chatbubble').hide();
	WIN_STATE = 'max';
	$('#status-msg').unbind('click', function() { maxChatWin(); return false; });
}

function setChatAvailable() {
//console.log('setChatAvailable');
	$('#status-msg').text('Chat available');
	$('#status-icon').removeClass();
	$('#status-icon').addClass('available');
	$('#chatbox-close, #chatting, #newchat').hide(); 
	$('#chatrequest').show();
	$('.title-status').text('');
	$('#titlebar').removeClass();
	$('#titlebar').addClass('available');
	$('#status-msg').bind('click', maxChatWin);
	
}

function setChatUnavailable() {
//console.log('setChatUnavailable');
	$('#status-msg').html('Chat unavailable' + " " + '<a href="'+CONTACT_FORM+'">contact us</a>');
	$('#status-icon').removeClass();
	$('#status-icon').addClass('unavailable');
	$('#newchat, #chatting, img.chatbox-close').hide();
	$('#status-msg').unbind('click', maxChatWin);
}

function setStatusUnavailable() {
//console.log('setStatusUnavailable');
	$('#status-msg').text('Chat unavailable');
	$('#status-icon').removeClass();
	$('#status-icon').addClass('unavailable');

}

function setChatWaiting() {
//console.log('setChatWaiting');
	$('#status-icon, #titlebar').removeClass();
	$('#status-icon, #titlebar').addClass('waiting');
	$('#status-msg').text('Waiting');
	$('.title-status').text('Waiting for a response...');
	$('#chatrequest, #chatinput, #newchat').hide();
	$('#chatting, #chathistory, #chatbox-close').show();
	maxChatWin();
	$('#status-msg').bind('click', maxChatWin); 
}

function setChatDisconnect() {
//console.log('setChatDisconnect');
	// update the chat state
	CHAT_STATE = 'disconnect';
	$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
	$.cookie('frontdesk', null, COOKIE_OPTIONS);
	//console.log('chat state: '+CHAT_STATE);	
    // Make things (in)visible
	$('#status-icon').removeClass();
	$('#status-icon').addClass('unavailable');
	$('#status-msg').html('Chat unavailable' + " " + '<a href="'+CONTACT_FORM+'">contact us</a>');
	$('#chatbox, #minimize, #chatinput, #newchat, #chatrequest').hide();
	$('.title-status').text('');
	$('#titlebar').removeClass();
	$('#titlebar').addClass('waiting');
	$('#chatting, #chathistory, #chatbox-close').show();
	var html = '<p>Your connection to our representative has been unexpectedly interrupted.</p>';
	html += '<p>Sometimes reloading the page can be helpful to solve this problem.</p>';
	clearChatHistory();
	updateChatHistory(html);
	maxChatWin();
}

function setChatting() {
//console.log('setChatting');
	if ( WIN_STATE == "min" || DOC_FOCUS === false  ) {
		soundManager.play('piano2-sound');
	}
	$('#status-msg').text('Chat available');
	$('#status-icon, #titlebar').removeClass();
	$('#status-icon').addClass('available');
	$('#titlebar').addClass('chatting');
	$('#chatting > *, #chatting').show();
	$('#chatbox-close').show(); 
	$('#chatrequest, #newchat').hide();
	$('.title-status').text('Chatting with a representative');
	$('.wait-status, .welcome-msg').text('');
	
	$("#text").focus(function() { 
		$('#status-msg').text('Chatting'); 
	});	
}

function setConnectFail() {
//console.log('setConnectFail');
    // Make things (in)visible
	$('#status-msg').html('Chat unavailable' + " " + '<a href="'+CONTACT_FORM+'">contact us</a>');
	$('#status-icon').removeClass();
	$('#status-icon').addClass('unavailable');
	$('#chatrequest, #newchat, #chatting, #chatting > *').hide();
}

function setChatEnded() {
//console.log('setChatEnded');
	$('#status-msg').unbind("click", maxChatWin);
	$('#status-msg').text('Chat ended');
	$('#status-icon').removeClass();
	$('#status-icon').addClass('ended');
	var i=0;
		while (i<=2){
			$('#status-msg').fadeOut(400).fadeIn(400);
			i++;
  		}
   setTimeout(function(){

		clearChatHistory();

    	// request to check status of queue
		var id = CONNECTION.getUniqueId('checkQueueStatus');
		var checkQstatIQ = $iq({
			'to': QUEUE,
			'type': 'get',
			'id': id
		}).c('query', {
			'xmlns': FDQUEUE + '_stats'
			});
		CONNECTION.addHandler(handleQstatusChatEnd, null, 'iq', null, id, null);
		CONNECTION.send(checkQstatIQ.tree());
		//console.log("from setChatEnded: " + checkQstatIQ.tree());
	}, 3000);
}

function requestNewChat(){
//console.log('requestNewChat');
	setChatAvailable();
	//setChatUnavailable();
	CHAT_STATE = 'available';
	$.cookie('frontdesk_state', CHAT_STATE, COOKIE_OPTIONS);
	clearChatHistory();
}

function clearChat(){
//console.log('clearChat');
	clearChatHistory();
	getNewConnection();
	minChatWin();
	requestQstatus("clearChat");
}

// functions for context

function contextButton(msg) {
	//console.log("CHAT_STATE: " + CHAT_STATE);
	if ( CONNECTION == null || CHAT_STATE == 'disconnect' || CHAT_STATE == 'unavailable' ){
		window.location=CONTACT_FORM;
	}
	else{
		//window.location=CONTACT_FORM;
		maxChatWin();
		$("#how").text(msg);
	}
}

function popout() {
	myWindow=window.open(POPOUT_URL,'popoutwindow','width=323,height=351,menubar=no,scrollbars=no,resizable=no,location=no');
	myWindow.focus();
}