// Controller for the "cfutablet" Widget.
var controller = (function($) {
	
 	var wwClient = qmatic.webwidget.client;
	var connectorClient = qmatic.connector.client;
	
	var attrKeys = {
		BUTTON1_TEXT : 'button1.text',
		BUTTON2_TEXT : 'button2.text',
		BUTTON3_TEXT : 'button3.text',
		BUTTON4_TEXT : 'button4.text',
		BUTTON5_TEXT : 'button5.text',
		
		BUTTON1_IMAGE : 'button1.image',
		BUTTON2_IMAGE : 'button2.image',
		BUTTON3_IMAGE : 'button3.image',
		BUTTON4_IMAGE : 'button4.image',
		BUTTON5_IMAGE : 'button5.image',

		BUTTON1_MARK : 'button1.mark',
		BUTTON2_MARK : 'button2.mark',
		BUTTON3_MARK : 'button3.mark',
		BUTTON4_MARK : 'button4.mark',
		BUTTON5_MARK : 'button5.mark',

		THANKYOU_TEXT : 'thankyou.text',
		THANKYOU_IMAGE : 'thankyou.image',
		THANKYOU_SHOW_TIME : 'thankyou.showTime',
		
		BUTTON_TEXTPOSITION : 'button.textPosition',
		
		WIDGET_BACKGROUND_COLOR : 'widget.background.color',
		
		VISIT_CALL_DELAY : 'visit.delay',

		BUTTON_LAYOUT : 'button.layout',
	};
	
	var attributeDefaults = new Array();
	attributeDefaults[attrKeys.BUTTON1_TEXT] = '';
	attributeDefaults[attrKeys.BUTTON2_TEXT] = '';
	attributeDefaults[attrKeys.BUTTON3_TEXT] = '';
	attributeDefaults[attrKeys.BUTTON4_TEXT] = '';
	attributeDefaults[attrKeys.BUTTON5_TEXT] = '';
	
	attributeDefaults[attrKeys.BUTTON1_IMAGE] = 'images/button1.png';
	attributeDefaults[attrKeys.BUTTON2_IMAGE] = 'images/button2.png';
	attributeDefaults[attrKeys.BUTTON3_IMAGE] = 'images/button3.png';
	attributeDefaults[attrKeys.BUTTON4_IMAGE] = 'images/button4.png';
	attributeDefaults[attrKeys.BUTTON5_IMAGE] = 'images/button5.png';

	attributeDefaults[attrKeys.BUTTON1_MARK] = '';
	attributeDefaults[attrKeys.BUTTON2_MARK] = '';
	attributeDefaults[attrKeys.BUTTON3_MARK] = '';
	attributeDefaults[attrKeys.BUTTON4_MARK] = '';
	attributeDefaults[attrKeys.BUTTON5_MARK] = '';
	
	attributeDefaults[attrKeys.THANKYOU_TEXT] = 'Thank you!';
	attributeDefaults[attrKeys.THANKYOU_IMAGE] = '';
	attributeDefaults[attrKeys.THANKYOU_SHOW_TIME] = 5;
	attributeDefaults[attrKeys.BUTTON_TEXTPOSITION] = 'after';
	attributeDefaults[attrKeys.BUTTON_LAYOUT] = 'horizontal';
	
	attributeDefaults[attrKeys.VISIT_CALL_DELAY] = 15;

	attributeDefaults[attrKeys.WIDGET_BACKGROUND_COLOR] = '#ffffff';
	
	var button1, button2, button3, button4, button5, thankyou, buttonPosition, 
		buttonLayout, pages, widgetBackgroundColor, visitCallDelay;
	var resetThankYouTimer, showCallTimer;
	var buttons = [];
	
	function getStringAttribute(attribParser, key) {
		return attribParser.getString(key, attributeDefaults[key]);
	}
	
	function getParsedInteger(attribParser, key) {
		return attribParser.getInteger(key, attributeDefaults[key]);
	}
	
	function getParsedImageUrl(attribParser, key) {
		return attribParser.getImageUrl(key, attributeDefaults[key]);
	}
	
	function setupAttributes(attr) {
		var attribParser = new qmatic.webwidget.AttributeParser(attr || {});
		
		buttonPosition = getStringAttribute(attribParser, attrKeys.BUTTON_TEXTPOSITION);
		buttonLayout = getStringAttribute(attribParser, attrKeys.BUTTON_LAYOUT);
		widgetBackgroundColor = getStringAttribute(attribParser, attrKeys.WIDGET_BACKGROUND_COLOR);
		visitCallDelay = getParsedInteger(attribParser, attrKeys.VISIT_CALL_DELAY);
		
		button1 = {
			text : getStringAttribute(attribParser, attrKeys.BUTTON1_TEXT),
			image : getParsedImageUrl(attribParser, attrKeys.BUTTON1_IMAGE),
			markName : getStringAttribute(attribParser, attrKeys.BUTTON1_MARK)
		};
		button2 = {
			text : getStringAttribute(attribParser, attrKeys.BUTTON2_TEXT),
			image : getParsedImageUrl(attribParser, attrKeys.BUTTON2_IMAGE),
			markName : getStringAttribute(attribParser, attrKeys.BUTTON2_MARK)
		};
		button3 = {
			text : getStringAttribute(attribParser, attrKeys.BUTTON3_TEXT),
			image : getParsedImageUrl(attribParser, attrKeys.BUTTON3_IMAGE),
			markName : getStringAttribute(attribParser, attrKeys.BUTTON3_MARK)			
		};
		button4 = {
			text : getStringAttribute(attribParser, attrKeys.BUTTON4_TEXT),
			image : getParsedImageUrl(attribParser, attrKeys.BUTTON4_IMAGE),
			markName : getStringAttribute(attribParser, attrKeys.BUTTON4_MARK)			
		};
		button5 = {
			text : getStringAttribute(attribParser, attrKeys.BUTTON5_TEXT),
			image : getParsedImageUrl(attribParser, attrKeys.BUTTON5_IMAGE),
			markName : getStringAttribute(attribParser, attrKeys.BUTTON5_MARK)			
		};
		thankyou = {
			text : getStringAttribute(attribParser, attrKeys.THANKYOU_TEXT),
			image : getParsedImageUrl(attribParser, attrKeys.THANKYOU_IMAGE),
			showTime : getParsedInteger(attribParser, attrKeys.THANKYOU_SHOW_TIME)
		};
		buttons = [button1, button2, button3, button4, button5];
	}
	
	function setupThankYouDetails() {
		var thankYouContainer = $('#cfoTabletThankYou');
		if(thankyou.image != '') {
			var thankYouImage = $('<img />').attr('src', thankyou.image);
			thankYouContainer.append(thankYouImage);
		}
		if(thankyou.text != '') {
			var thankYouText = $('<span />').html(thankyou.text);
			thankYouContainer.append(thankYouText);
		}
	}
		
	function getVoteButton(buttonName, button) {
		var result = $('<li />');
		result.attr('data-button-id', buttonName);
		var spanClass = buttonPosition;
		if(button.image != '') {
			var img = $('<img></img>').attr('src', button.image);
			result.append(img);
		}
		if(button.text != '') {
			var span = $('<span />').html(button.text).addClass(spanClass);
			if(spanClass == 'before') {
				result.prepend(span);
			} else {
				result.append(span);
			}
		}
		return result;
	}
	
	/* require text or image AND a mark set for the button */
	function isVoteButtonEnabled(button) {
		return (button.text != '' || button.image != '') && button.markName != '';
	}
	
	function setupContentPage() {
		$('#cfoTabletVote').addClass(buttonLayout);
		var container = $('#cfoTabletVote ul:first');
		for(var i=0;i<buttons.length;i++) {
			if(isVoteButtonEnabled(buttons[i])) {
				var buttonName = 'button' + (i + 1);
				var button = getVoteButton(buttonName, buttons[i]);
				container.append(button);
			}
		}
	}
	
	function showBlank() {
		$('#cfoTabletVote').hide();
		$('#cfoTabletThankYou').hide();
	}
	
	function showThankYou() {
		$('#cfoTabletVote').hide();
		$('#cfoTabletThankYou').show();
	}
	
	function setupAndshowVotePage(branchId, servicePointLogicId, visitId, waitingTime, serviceId) {
		$('#cfoTabletVote li').each(function(key, item) {
			var buttonName = $(item).attr('data-button-id');
			var button = getButtonFromName(buttonName);
			if(isVoteButtonEnabled(button)) {
				setVoteDetailsToItem(item, branchId, servicePointLogicId, visitId, button.markName, waitingTime, serviceId);
				$(item).unbind('click');
				$(item).click(function() {
					var voteDetails = getVoteDetailsFromItem(this);
					onCustomerVote(voteDetails.branchId, voteDetails.servicePointId, voteDetails.visitId, 
						voteDetails.markName, voteDetails.waitingTime, voteDetails.serviceId);
				});
			}
		});
		$('#cfoTabletThankYou').hide();
		$('#cfoTabletVote').show();
	}
	
	function getButtonFromName(name) {
		if(name == 'button1') {
			return button1;
		} else if(name == 'button2') {
			return button2;
		} else if(name == 'button3') {
			return button3;
		} else if(name == 'button4') {
			return button4;
		} else if(name == 'button5') {
			return button5;
		}
	}
	
	function setVoteDetailsToItem(item, branchId, servicePointId, visitId, markName, waitingTime, serviceId) {
		$(item).attr('data-branch-id', branchId);
		$(item).attr('data-servicepoint-id', servicePointId);
		$(item).attr('data-visit-id', visitId);
		$(item).attr('data-mark-name', markName);
		$(item).attr('data-waiting-time', waitingTime);
		$(item).attr('data-service-id', serviceId);
	}
	
	function getVoteDetailsFromItem(item) {
		return {
			'markName' : $(item).attr('data-mark-name'),
			'servicePointId' : $(item).attr('data-servicepoint-id'),
			'visitId' : $(item).attr('data-visit-id'),
			'branchId' : $(item).attr('data-branch-id'),
			'waitingTime' : $(item).attr('data-waiting-time'),
			'serviceId' : $(item).attr('data-service-id')
		}
	}	
	
	function switchToFirstPage() {
		wwClient.switchHostPage('startpage', true);
	}
	
	function switchToSecondPage() {
		wwClient.switchHostPage('callpage', true);
	}
	
	function onCustomerVote(branchId, servicePointLogicId, visitId, markName, waitingTime, serviceId) {
		showThankYou();
		resetThankYouTimer = setTimeout(function() { 
			showBlank(); switchToFirstPage(); 
		}, thankyou.showTime * 1000);
		
		registerMarkOnVisit(branchId, servicePointLogicId, visitId, markName);
		registerStatForVisit(serviceId, markName, waitingTime);
	}
	
	function registerMarkOnVisit(branchId, servicePointLogicId, visitId, markName) {
		connectorClient.addMarkByName(branchId, visitId, markName, servicePointLogicId);
	}
	
	function registerStatForVisit(serviceId, waitingTime, markName) {
		statCFUData.updateMarkVariable(serviceId, waitingTime, markName);
	}

	function setWidgetBackground() {
		$('body:first').css('background-color', widgetBackgroundColor);
	}
	
	function onServicePointClose(topic, publisherData, subscriberData) {
		resetCFUEvent(topic, publisherData, subscriberData);
	}

	function onVisitNext(topic, publisherData, subscriberData) {
		resetCFUEvent(topic, publisherData, subscriberData);	
	}
	
	function onVisitEnd(topic, publisherData, subscriberData) {
		resetCFUEvent(topic, publisherData, subscriberData);
	}
	
	function resetCFUEvent(topic, publisherData, subscriberData) {
		clearTimeout(resetThankYouTimer);
		clearTimeout(showCallTimer);
		showBlank();
		switchToFirstPage();		
	}
	
	function onCustomerCalledEvent(topic, publisherData, subscriberData) {
		clearTimeout(resetThankYouTimer); //reset timer for switching from "thank you"-message
		clearTimeout(showCallTimer); //reset so we don't trigger twice
		showBlank();
		switchToFirstPage(); 
		
		var branchId = publisherData.prm.branchId;
		var servicePointLogicId = publisherData.prm.servicePointLogicId;
		var serviceId = publisherData.prm.serviceOrigId;
		var visitId = publisherData.prm.visitId;
		var date = publisherData.prm.callTime;
		var waitingTime = publisherData.prm.waitingTime;

		setDateInStatistics(date);
		setMarksInStatistics();
		showCallTimer = setTimeout(function() {
			setupAndshowVotePage(branchId, servicePointLogicId, visitId, waitingTime, serviceId);
			switchToSecondPage();
			
		}, visitCallDelay * 1000);
	}
	
	function setDateInStatistics(rawDate) {
		var date = formatEventDate(rawDate);
		statCFUData.setCurrentDate(date);
	}
	
	function setMarksInStatistics() {
		var markNames = getAllMarkNames();
		statCFUData.setMarkNames(markNames);
	}
	
	function getAllMarkNames() {
		var markNames = [];
		for(var i=0;i<buttons.length;i++) {
			if(isVoteButtonEnabled(buttons[i])) {
				markNames.push(buttons[i].markName);
			}
		}
		return markNames;		
	}
	
	function formatEventDate(date) {
		if(date.length > 9)
			return date.substring(0, 10);
		return date;
	}
	
	// Public content of controller
	return {
		/**
		 * Called when widget client has finished loading. This is where you initialize your widget
		 */
		onLoaded : function(configuration) {
			var attr = configuration.attributes;
			setupAttributes(attr);
			setWidgetBackground();
			setupContentPage();
			setupThankYouDetails();			
			wwClient.subscribe(qmatic.webwidget.topic.VISIT_CALL, onCustomerCalledEvent);
			wwClient.subscribe(qmatic.webwidget.topic.SERVICE_POINT_CLOSE, onServicePointClose);

			//not supported for positional displays in 5.2.3
			//wwClient.subscribe(qmatic.webwidget.topic.VISIT_NEXT, onVisitNext);
			//wwClient.subscribe(qmatic.webwidget.topic.VISIT_END, onVisitEnd);			
		},		
		onLoadError : function(message) {
			$('body').append('<p>Widget load error: ' + message + '</p>');
		}
	};	
	
})(jQuery);
