// -----------------------------------------------------
// 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 
 */


function toogleTalkNowMoreInfo() {
    if ($('talkNowMoreInfo').innerHTML=='') {
        $('talkNowMoreInfo').innerHTML = TalkNowInput.MoreInfo;	
    } else {
        $('talkNowMoreInfo').innerHTML = '';
    }
}



var myAvailableCallback = function availableCallback( isAvailable ) {	
    // dessa finns i template-frag.html (span element)
	// var presenceText = $('talkNowPresence');
	
	var presenceImage = $('talkNowPresenceImage');
	
	if( isAvailable ) {
	 	// Someone from the requested group is available, change the image and text to show this
	 	$('talkNowMessage').innerHTML = "Skriv in ditt telefonnummer, s&aring; ringer vi dig nu"	
	} else {
	 	// Someone from the requested group is not available, change the image and text to show this
	 	$('talkNowMessage').innerHTML = "Skriv in ditt telefonnummer, s&aring; ringer vi dig nu"
	}
};

/**
 * 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 ) {
    // ett svar har kommit från lekane
	var messageText = $('talkNowMessage');
	
	
	$('talkNowPresenceImage').setAttribute( 'style','display:none' );
	
	// 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 = 'Tack f&ouml;r att ni kontaktar oss, ' + caller + ' kommer ringa upp er nu'; 
	} else {
	 	// No one has accepted the call request within the time period, so we display that someone will contact them
	 	messageText.innerHTML = 'Vi &auml;r tyv&auml;rr upptagna nu, men vi ringer upp er s&aring; snart som m&ouml;jligt'; 
	 	//messageText.innerHTML = 'Vi &auml;r tyv&auml;rr upptagna nu, men vi kommer ringa tillbaka s&aring; snart som m&ouml;jligt';
	}
};

/**
 * 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();
	
	//var isValid = /^[+]?[0-9\s]{6,13}$/.test($('phoneNumber').value)
	var isValid = /^[0-9]{6,13}$/.test($('phoneNumber').value)
	
    
    
    
	if (isValid == false || $F('phoneNumber').length == 0) {
		//if (isValid) {
			
			alert('Skriv in ert telefonnummer (endast siffror utan bindestreck eller mellanslag)');
		//}
		return;
	}

	// Get the phone number from the form and append to the end of other data.
	// data är en global array av name-value-par
	var phoneNumberTextField = $('phoneNumber');
	data[0][data[0].length] = 'phoneNumber';
	data[1][data[1].length] = phoneNumberTextField.value;
	
	data[0][data[0].length] = 'Make';
	data[1][data[1].length] = TalkNowInput.Make;	
	
	data[0][data[0].length] = 'Mileage';
	data[1][data[1].length] = TalkNowInput.Mileage;	
	
	data[0][data[0].length] = 'Model';
	data[1][data[1].length] = TalkNowInput.Model;	
	
	data[0][data[0].length] = 'ModelDetails';
	data[1][data[1].length] = TalkNowInput.ModelDetails;	
	
	data[0][data[0].length] = 'Price';
	data[1][data[1].length] = TalkNowInput.Price;	
	
	data[0][data[0].length] = 'Registration';
	data[1][data[1].length] = TalkNowInput.Registration;	
	
	
	
	// lägg till fler properties
	
	// 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.


    $('talkNowMoreInfoWrap').parentNode.removeChild($('talkNowMoreInfoWrap'));
        
    $('talkNowPresenceImage').setAttribute( 'style','display:inline' );


	// Update text also.
	$('talkNowMessage').innerHTML = 'Skickar...';
	
    // 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( 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', localTalkNowURL+'/talknow-template-frag.html', {
		  		method: 'get',
		  		onComplete: function( done ) {
					// Wire up the validator
					// validator = new Validation('talkNowForm', {immediate : true}); 
					myAvailableCallback( available );		
		  		}	
		  	});

			// Now check the presence every 30 seconds.
			// behövs troligen inte
/*			
			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.

	  	} 
	});
}

