// -----------------------------------------------------
// 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

// -----------------------------------------------------

/**
 * 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 = 'Apteekissamme on t&auml;ll&auml; hetkell&auml; vapaita farmaseutteja valmiina palvelemaan sinua luottamuksellisesti';
	 	presenceImage.setAttribute( 'src','/images/ready.png' );
	 	messageText.innerHTML = "Anna puhelinnumerosi, niin vapaana oleva farmaseutti soittaa soittaa sinulle tuota pikaa takaisin!"; 	
	} else {
	 	// Someone from the requested group is not available, change the image and text to show this
		presenceText.innerHTML = 'Valitettavasti kaikki farmaseuttimme ovat t&auml;ll&auml; hetkell&auml; varattuja, tai liikkeemme on suljettu';
	 	presenceImage.setAttribute( 'src','/images/notready.png' );
	 	messageText.innerHTML = "Voit kuitenkin j&auml;tt&auml;&auml; soittopyynn&ouml;n oheisen yhteydenottolomakkeen avulla, niin soitamme sinulle takaisin heti kun ensimm&auml;inen farmaseuttimme on vapaana!";
		
	}
};

/**
 * 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 = 'Kiitos yhteydenotosta, ' + caller + ' soittaa sinulle takaisin nyt...'; 	
	} else {
	 	// No one has accepted the call request within the time period, so we display that someone will contact them
	 	messageText.innerHTML = 'Valitettavasti olemme juuri nyt varattuja, mutta soitamme takaisin mahdollisimman nopeasti.';
	}
};

/**
 * 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('Sy&ouml;t&auml; toimiva puhelinnumero (vain numeroita)');
		}
		return;
	}

	// Get the phone number from the form and append to the end of other data.
	
	data[0][0] = 'phoneNumber';
    data[1][0] = $('phoneNumber').value;
    data[0][1] =  'Product';
    data[1][1] = $('Product').value;
    data[0][2] = 'Category';
    data[1][2] = $('Category').value;
    data[0][3] = 'ShoppingBasket';
    data[1][3] = $('ShoppingBasket').value;
	data[0][4] = 'Entity_ID';
    data[1][4] = $('Entity_ID').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','/images/processing.gif' );

	// Update text also.
	var statusMessageText = $('talkNowStatusMessage');
	statusMessageText.innerHTML = 'L&auml;hetet&auml;&auml;n pyynt&ouml;&auml;...';
	
	var messageText = $('talkNowMessage');
	messageText.innerHTML = '';

    // Remove form to minimize double submits.
    var talkNowForm = $('talkNowForm');
    talkNowForm.parentNode.removeChild( talkNowForm );	
	
	// Call TalkNow send request
	sendCallRequest( searchPattern, data, metadata, myCallRequestCallback );
}

/**
 *  Enable TalkNow content if server is up and running.
 */
function enableTalkNowIfServerIsActive(https) {
var protocol='http';	
var pekanurl='://www.internetapteekki.fi/talknow-template-frag.php';

if ( https === undefined ) {
      https = '';
   }

	// Request the status directly
	new Ajax.Request(proxyURL , { 
	method: 'post',
	parameters: 'url=' + lekaneServerURL + '/lekane/TalkNowStatus&cmd=availability&deployment=' + encodeURIComponent( talkNowDeploymentId ) + '&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', protocol + https + pekanurl, {
		  		method: 'get',
		  		onComplete: function( done ) {
					// Wire up the validator
					validator = new Validation('talkNowForm', {immediate : true}); 
					myAvailableCallback( available );		
		  		}	
		  	});		
			
		},
		onException: function(req, e){
	    	 // Lekane TalkNow server is not running. Do not replace the div content, with the live status.
	  	} 
	});
}

