// -----------------------------------------------------
// TalkNow template javascript for customer integration. 
// This is intended as an example for customers to follow to add TalkNow to their website.
// 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', 'Please enter a valid phone number (digits only)',  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 presenceCallBack expects a boolean variable for true indicating that
 * someone from the requested group is available or false if they aren't.
 * @param isAvailable boolean 
 */
var myAvailableCallback = function availableCallback( isAvailable ) {	
	var presenceText = $('talkNowPresence');
	var messageText = $('talkNowMessage');
	var presenceImage = $('talkNowPresenceImage');
	
	if( isAvailable ) {
	 	// Someone from the requested group is available, change the image and text to show this
		presenceText.innerHTML = 'available';
	 	presenceImage.setAttribute( 'src', localTalkNowURL + '/talknow/images/ready.png' );
	 	messageText.innerHTML = "Please enter your phone number and we'll call you now."; 	
	} else {
	 	// Someone from the requested group is not available, change the image and text to show this
		presenceText.innerHTML = 'busy';
	 	presenceImage.setAttribute( 'src', localTalkNowURL + '/talknow/images/notready.png' );
	 	messageText.innerHTML = "Please leave your phone number and we'll call you as soon as possible.";
	}
};

/**
 * 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, callerPictureUrl ) {
	var messageText = $('talkNowMessage');
	
	// Remove presence details.
	var presenceParagraph = $('talkNowPresenceParagraph');
	presenceParagraph.parentNode.removeChild( presenceParagraph );
	
	// If the caller hasn't been set it comes through to javascript as null
	if( caller != null && caller != '' ) {
	 	// Someone from the requested group has accepted the call request and will call the customer back
	 	messageText.innerHTML = 'Thank you for contacting us, ' + caller + ' will call you back now.'; 	
	} else {
	 	// No one has accepted the call request within the time period, so we display that someone will contact them
	 	messageText.innerHTML = 'Unfortunately we are busy, but we will call you back as soon as possible.';
	}
};

/**
 * 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.
 * This technique can be used to add any data input by the user that are required to be broadcast to the mobile phones.
 */
function sendRequest() {
	// 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 a valid phone number (digits only)');
		}
		return;
	}

	// Get the phone number from the form and append to the end of other data.
	var phoneNumberTextField = $('phoneNumber');
	data[0][data[0].length] = 'phoneNumber';
	data[1][data[1].length] = phoneNumberTextField.value;
	// Further data can be passed to the TalkNow server in this way.
	
	// 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 + '/talknow/images/processing.gif' );

	// Update text also.
	var statusMessageText = $('talkNowStatusMessage');
	statusMessageText.innerHTML = 'Sending request...';
	
	var messageText = $('talkNowMessage');
	messageText.innerHTML = '';

    // Remove form to minimize double submits.
    var talkNowForm = $('talkNowForm');
    talkNowForm.parentNode.removeChild( talkNowForm );
	
	stopPoller = true;
	
	// Call TalkNow send request
	sendCallRequest( searchPattern, data, metadata, myCallRequestCallback );
}

/**
 *  Enable TalkNow content if server is up and running.
 */
function enableTalkNowIfServerIsActive() {	
	// Request the status directly
	new Ajax.Request(proxyURL , { 
	method: 'post',
	parameters: 'url=' + lekaneServerURL + '/lekane/TalkNowStatus&cmd=availability&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 available = -1 != responseDetails.responseText.indexOf('true');

			// Replace the talknow div with content
		  	new Ajax.Updater('talknow', localTalkNowURL+'/talknow/fragments/talknow-template-frag_' + talkNowLang + '.html', {
		  		onComplete: function( done ) {
					// Wire up the validator
					validator = new Validation('talkNowForm', {immediate : true}); 
					myAvailableCallback( available );		
		  		}	
		  	});

			// Now check the presence every 30 seconds.
			new PeriodicalExecuter( function(pe) { 
				if ( !stopPoller ) {
					isAvailable( searchPattern, myAvailableCallback );
				} else {
					pe.stop();
				}
			}, 30);
		},
		onException: function(req, e){
	    	 // Lekane TalkNow server is not running. Do not replace the div content, with the live status.
	  	} 
	});
}
