// Controller for the "ding" Widget. Background color isn't used, but left so we know where to add sound file URL later on...
var controller = (function($) {
	
	var NUMBER_OF_AUDIO_TAGS = 3;
	var currentIndex = 0;
	
	var attributes,	audioUrl,			
		wwClient = qmatic.webwidget.client,
		attributeKeys = {
			DING_FILE   			: 'ding.file'
		},
		attributeDefaults = {};
	
	
	
	attributeDefaults[attributeKeys.DING_FILE] = 'sound/ding.wav';
	
	function onCustomerCalledEvent(topic, publisherData, subscriberData) {
		
		$('#newTicketSound_' + currentIndex)[0].play();
		
		if(currentIndex + 1 >= NUMBER_OF_AUDIO_TAGS) {
			currentIndex = 0;
		} else {
			currentIndex++;
		}
	}

	// Public contents of controller
	return {
		/**
		 * Called when widget client has finished loading. This is where you initialise your widget
		 */
		onLoaded : function(configuration) {
			var attr = configuration.attributes;
			
			var attribParser = new qmatic.webwidget.AttributeParser(attr || {}),
				defaultsParser = new qmatic.webwidget.AttributeParser(attributeDefaults),
				ak = attributeKeys;				
			audioUrl = attribParser.getAudioUrl(ak.DING_FILE, attributeDefaults[ak.DING_FILE]);
			
			attributes = attr;
			
			// Due to a problem with a single audio tag unable to play several samples at the same time,
			// we create several audio tags.
			for(var i = 0; i < NUMBER_OF_AUDIO_TAGS; i++) {
				$('#content').append('<audio id="newTicketSound_' + i + '" src="' + audioUrl + '" preload="auto"></audio>');
			}
			currentIndex = 0;
			
			// Subscribe to customer called so we can play the ding when an event is recieved.
			// Depending on which display type we're running on, we need to subscribe to different events.
			if(configuration.displayType == 'MEDIA' || configuration.displayType == 'TOUCH') {
				wwClient.subscribe(qmatic.webwidget.topic.VISIT_CALL, onCustomerCalledEvent);
			} else if(configuration.displayType == 'POSITIONAL') {
				wwClient.subscribe(qmatic.webwidget.topic.VISIT_CALL, onCustomerCalledEvent);
			} else {
				// MAIN?
				wwClient.subscribe(qmatic.webwidget.topic.VISIT_CALL, onCustomerCalledEvent);
			}
		},
		
		onLoadError : function(message) {
			$('body').append('<p>Widget load error: ' + message + '</p>');
		}
	};	
	
})(jQuery);