// -----------------------------------------------------
// Lekane TalkNow - build for Lekane.com frontpage
// Copyright Lekane 2008
// -----------------------------------------------------

// Create the validator once we have loaded the page fragment (dependant on if the TalkNow server responds)
var validator;
Validation.add('phone', 'invalid phone number',  function (v) { return /^[+]?[0-9\s]{6,13}$/.test(v)}); 

// Stop the periodic presence check as we want to wait for the response from send call request
var stopPoller = false;
// -----------------------------------------------------

/**
 * This is where you define what you want to do when you receive a presence response.
 * The whoIsAvailableCallback expects an array of user id's paired with display names.
 * @param availableUsers[][] id matched with display name array
 */
var myWhoIsAvailableCallback = function whoIsAvailableCallback( availableUsers ) {
	
	// We are using the prototype shorthand for getting the elements on the sample.html page.
	var dropDown = $('userDropDown');
	var dropDownSpan = $('userToTarget');
	var presenceText = $('talkNowPresenceText');
	var presenceImage = $('talkNowPresenceImage');
	
	// Create new dropdown list items
	if(null == availableUsers || availableUsers =='') {
		dropDownSpan.hide();
		presenceImage.setAttribute( 'src', localTalkNowURL+'phone-notready.gif' );
		presenceText.innerHTML = 'We are currently busy';
		initSearchBox();
	} else {
		dropDownSpan.show();
		presenceImage.setAttribute( 'src', localTalkNowURL+'phone-ready.gif' );
		presenceText.innerHTML = 'We are ready to talk to you'; 	
		
		// Get the previously selected item (as the lekane demo refreshes - its annoying if the selection is lost
		// when we rebuild the dropdown)
		var previouslySelected = dropDown.options[dropDown.selectedIndex].value;
		initSearchBox();
		
		// Split the list of users into value and text to display and add them to the box
		var keyValues = availableUsers.split('|');
		var count = 1;

		for( var i=0; i < keyValues.length; i=i+2 ) {
			var text = keyValues[i];
			var value = keyValues[i+1];
			var option = new Option( text, value );
			
			if ( value == previouslySelected ) {
				option.selected = true;
			}
			dropDown.options[count] = option;
			count = count + 1;
		}
	}
};

function initSearchBox() {
	var dropDown = $('userDropDown');
	// Clear the select box
	while (dropDown.firstChild){
		dropDown.removeChild(dropDown.firstChild);
	}	

	// Add the 'everyone' option mapped to LekaneWeb group
	var option = new Option( 'Everyone', searchPattern );
	option.selected = true;
	dropDown.appendChild(option);
}

/**
 * This is where you define what you want to do when you receive a response to the callback request.
 * @param caller is who will be calling the web user back, or null if the request timed out.
 */
var myCallRequestCallback = function callRequestCallback( caller, callerId ) {
	
	// We are using the prototype shorthand for getting the elements on the sample.html page.
	var presenceText = $('talkNowPresenceText');
	var presenceImage = $('talkNowPresenceImage');
	
	// If the caller hasn't been set it comethrough to javascript as null
	if(caller != null && caller != '') {
	 	// Someone from the requested group has accepted the call request and will call the customer back
	 	presenceImage.setAttribute( 'src', localTalkNowURL+'phone-ready.gif' );
		presenceText.innerHTML = caller.unescapeHTML() + ' will call you back'; 	
	} else {
	 	// No one has accepted the call request within the time period, so we display that someone will contact them
	 	presenceImage.setAttribute( 'src', localTalkNowURL+'phone-notready.gif' );
		presenceText.innerHTML = 'We are currently busy, we will call you back soon';
	}
};



/**
 * An example function that shows the format of the data to send to TalkNow server.
 * This example takes some data that was generated on the server side of the form key and value's
 * stored in an Array. It adds in the phone number entered on the web page and uses the user Id from the
 * dropdown menu (real time updated with available users).
 */
function callRequestData() {
	// Manually run the validator to see if we should submit
	var isValid = validator.validate();

	if (isValid == false || $F('phoneNumber').length == 0) {
		if (isValid) {
			// IE 5.5 is not properly supported by prototype and the validator just tell the user to type a phone number 
			alert('Please enter your phone number');
		}
		return;
	}
	
	// Further data can be passed to the TalkNow server in this way.
	data[0][0] = 'phoneNumber';
	data[1][0] = $F('phoneNumber');
	
	var notes = $F('notes');
	data[0][1] = 'notes';
	data[1][1] =  notes;
	
	// This example changes the phone image to an animated icon to give the web user feedback that something is happening.
	var presenceImage = $('talkNowPresenceImage');
	presenceImage.setAttribute( 'src', localTalkNowURL+'phone-in-progress.gif' );
	
	// Get the currently selected user from the dropdown
	var dropDown = $('userDropDown');
	var searchPattern = dropDown.options[dropDown.selectedIndex].value;
	
	stopPoller = true;
	
	sendCallRequest( searchPattern, data, metadata, myCallRequestCallback );
}

/**
 * Toggle the visibility  of the object with the given id.
 */
function setVisibility( objectToShow ) {
	// Get the id of the form
	var obj = $(objectToShow);
	if (obj.style.display=="none") {
		new Effect.SlideDown(obj);
	}
	else {
		new Effect.SlideUp(obj);
	}	
}

/**
 *  Retrieve TalkNow content and display on page
 */
function enableTalkNowIfServerIsActive() {
	
	// Request the status directly - we're cheating here and using the request as a way to detect if the server is up and running.
	new Ajax.Request(proxyURL , {
	method: 'post',
	parameters: 'url=' + lekaneServerURL + '/lekane/TalkNowStatus&cmd=details&deployment=' + encodeURIComponent(deploymentId) + '&searchPattern=' + encodeURIComponent(searchPattern),
	onSuccess: function( responseDetails ) {
	  		// We got a response - replace the content of the div with the talk now fragment
			var isAvailable = responseDetails;

			// Replace the talknow div with content
		  	new Ajax.Updater('talknow', localTalkNowURL+'/talknow.fragment', {
		  		onComplete: function( done ) {
					// Wire up the validator
					validator = new Validation('myform', {immediate : true}); 

					// We've loaded in the talknow fragment - use the callback to set the availability
		  			var availableArray = null;
	  				if( null != isAvailable.responseText  && isAvailable.responseText.length > 0 ) {
						availableArray = isAvailable.responseText.strip(); 
					}
					myWhoIsAvailableCallback( availableArray );		
		  		}	
		  	});

			// Now check the presence every 30 seconds.
			new PeriodicalExecuter( function(pe) { 
				if ( !stopPoller ) {
					whoIsAvailable( searchPattern, myWhoIsAvailableCallback );
				} else {
					pe.stop();
				}
			}, 30);
		},
		onException: function(req, e){
	    	 // Lekane TalkNow server is not running. Do not replace the div content, with the live status.
	  	} 
	});
}
