
var controller = (function($) {
	
	var attributes,
		globalTicketText, globalTicketTextColor, globalTicketTextFontFamily, globalTicketTextFontSize,
        globalTicketTextFontStyle, globalTicketTextFontWeight, globalCounterText, globalShowDirection, globalLeftArrow,
        globalRightArrow, globalFlashDuration, globalShowFrame, globalFrameRadius, globalFlashSpeed,
        globalShowCustomerName, globalCustomerNameFontSize, globalCustomerNameFontFamily, globalCustomerNameFontStyle,
        leftArrowTemplate = '<img id="left_arrow" src="{{leftArrowUrl}}" style="visibility:hidden;"/>',
		rightArrowTemplate = '<img id="right_arrow" src="{{rightArrowUrl}}" style="visibility:hidden;"/>',
		entryTemplate = '<div class="ticketEntry">' +
							'<div id="border" style="background-color:transparent;float:left;position:absolute;width: 100%;height:100%;z-index:-1;"></div>' + 
							'<div id="ticketDimensions" style="height: 100%; width: 100%; margin-top: 40px;">' +
								'<div style="overflow: hidden; text-align: center;">' +
									'<div class="text_element">{{ticketText}}</div>' +
									'<div id="ticketNumber" class="ticketNumberStyle">{{ticketNumber}}</div>' +
									'<div class="stationNameStyle">' +
										'<table align="center" class="stationNameStyle"><tr>' +
											'<td id="td_left_arrow"></td>' +
											'<td>{{workstationName}}</td>' +
											'<td id="td_right_arrow"></td>' +
										'</tr></table></div>' +
								'</div>' +
							'</div>' +
						'</div>',
		wwClient = qmatic.webwidget.client,
		attributeKeys = {
			TICKET_TEXT                 : 'text.above.ticket',
            TICKET_TEXT_COLOR           : 'text.above.ticket.color',
            TICKET_TEXT_FONT            : 'text.above.ticket.font',
            COUNTER_TEXT                : 'text.for.counter',
			TICKET_TOP_MARGIN           : 'top.margin',
			TICKET_BACKGROUND_COLOR		: 'ticket.background.color',
			TICKET_BACKGROUND_TRANSPARENCY : 'ticket.background.transparency',
			TICKET_NUMBER_COLOR			: 'ticket.number.color',
			TICKET_NUMBER_FONT			: 'ticket.number.font',
			TICKET_STATION_COLOR		: 'ticket.station.color',
			TICKET_STATION_FONT			: 'ticket.station.font',
			TICKET_SHOW_DIRECTION       : 'show.direction',
			TICKET_LEFT_ARROW           : 'arrow.left.image',
			TICKET_RIGHT_ARROW          : 'arrow.right.image',
			TICKET_FLASH_DURATION       : 'flash.duration',
			SHOW_FRAME                  : 'show.frame',
			FRAME_RADIUS                : 'frame.radius',
			FLASH_SPEED		              : 'flash.speed',
			USE_SP_NAME                 : 'use.sp.name',
			SHOW_CUSTOMER_NAME          : 'show.customername',
			CUSTOMER_NAME_FONT      		: 'customername.font'
		},
		attributeDefaults = {},
        ticketCall;
        var useSpName = false;
	
	function onCustomerCalledEvent(topic, publisherData, subscriberData) {
		var resultHtml;
		
		if (publisherData && publisherData.prm.ticket) {
			$('#ticketCall').empty();
			// qmatic.webwidget.client.logInfo('Callwidget: Monitor event (9) received. Ticket: ' + publisherData.prm.ticket + ', Workstation: ' + publisherData.prm.servicePointLogicId);
			
			var isCustomerName = false;
			
			if(globalShowCustomerName == 0 || publisherData.prm.customers == '' || publisherData.prm.customers === undefined) {
			  resultHtml = entryTemplate.replace(/\{\{ticketNumber\}\}/g, publisherData.prm.ticket) || '';
			} else {
			  
			  var firstName = publisherData.prm.customers.split(' ').slice(0, -1).join(' ');
        var lastName = publisherData.prm.customers.split(' ').slice(-1).join(' ');
        var fullName = '';
        
  			switch(globalShowCustomerName) {
      		case 1:
      		  // John Doe
      		  fullName = publisherData.prm.customers;
  			    isCustomerName = true;
      		  break;
      		case 2:
      		  // J. Doe
      		  var firstNames = firstName.match(/\b(\w)/g);
  			    firstName = firstName.length > 0 ? firstNames.join('. ') + '. ' : '';
  			    fullName = firstName + lastName;
  			    isCustomerName = true;
      		  break;
      		case 3:
      		  // John D.
            firstName = firstName.length > 0 ? firstName + ' ' : '';
  			    lastName = lastName.length > 0 ? lastName.substring(0,1) + '.' : '';
  			    fullName = firstName + lastName;
  			    isCustomerName = true;
      		  break;
  			  default:
      		  fullName = entryTemplate.replace(/\{\{ticketNumber\}\}/g, publisherData.prm.ticket) || '';;
      		  isCustomerName = false;
      			break;
        }    			
		    resultHtml = entryTemplate.replace(/\{\{ticketNumber\}\}/g, fullName) || '';
      }
      
			if (useSpName) {			
				resultHtml = resultHtml.replace(/\{\{workstationName\}\}/g, (publisherData.prm.servicePointName || ''));
			} else {
  			resultHtml = resultHtml.replace(/\{\{workstationName\}\}/g, globalCounterText + ' ' + (publisherData.prm.servicePointLogicId || ''));
  		}
			resultHtml = resultHtml.replace(/\{\{ticketText\}\}/g, (globalTicketText || ''));
			
			// Handle left/right arrow. Make sure POSITIONAL displays never can show arrows.
			if(wwClient.getDisplayType() != 'POSITIONAL' && globalShowDirection == true) {
				var leftArrow = leftArrowTemplate.replace(/\{\{leftArrowUrl\}\}/g, (globalLeftArrow || ''));
				var rightArrow = rightArrowTemplate.replace(/\{\{rightArrowUrl\}\}/g, (globalRightArrow || ''));

                var isLeft = publisherData.prm.isLeft;
                var isRight = publisherData.prm.isRight;

                ticketCall.addEntry({
                    html: resultHtml,
                    leftArrow: leftArrow,
                    rightArrow: rightArrow,
                    showDirection: isLeft ? 'left' : isRight ? 'right' : 'none',
                    flashDuration: globalFlashDuration,
                    flashSpeed: globalFlashSpeed,
                    isCustomerName: isCustomerName
                });

				
			} else {
				ticketCall.addEntry({
					html: resultHtml,
					showDirection: 'none',
					flashDuration: globalFlashDuration,
          flashSpeed: globalFlashSpeed,
          isCustomerName: isCustomerName
				});
			}
			
		}
	}
	
	attributeDefaults[attributeKeys.TICKET_TEXT] = 'Now serving';
    attributeDefaults[attributeKeys.TICKET_TEXT_COLOR] = '#000000';
    attributeDefaults[attributeKeys.TICKET_TEXT_FONT] = 'Helvetica;46px;normal;normal';
    attributeDefaults[attributeKeys.COUNTER_TEXT] = 'Counter';
	attributeDefaults[attributeKeys.TICKET_TOP_MARGIN] = '40';
	attributeDefaults[attributeKeys.TICKET_BACKGROUND_COLOR] = '#E5EDFF';
	attributeDefaults[attributeKeys.TICKET_BACKGROUND_TRANSPARENCY] = 100;
	attributeDefaults[attributeKeys.TICKET_NUMBER_COLOR] = '#000000';
	attributeDefaults[attributeKeys.TICKET_NUMBER_FONT] = 'Helvetica;46px;normal;normal';
	attributeDefaults[attributeKeys.TICKET_STATION_COLOR] = '#000000';
	attributeDefaults[attributeKeys.TICKET_STATION_FONT] = 'Helvetica;28px;normal;normal';
	attributeDefaults[attributeKeys.TICKET_SHOW_DIRECTION] = 'false';
	attributeDefaults[attributeKeys.TICKET_LEFT_ARROW] = 'images/red_left_small.png';
	attributeDefaults[attributeKeys.TICKET_RIGHT_ARROW] = 'images/red_right_small.png';
	attributeDefaults[attributeKeys.TICKET_FLASH_DURATION] = 2700;
	attributeDefaults[attributeKeys.SHOW_FRAME] = true;
	attributeDefaults[attributeKeys.FRAME_RADIUS] = 15;
	attributeDefaults[attributeKeys.FLASH_SPEED] = 600;
	attributeDefaults[attributeKeys.SHOW_CUSTOMER_NAME] = 0; // 0 = Do not show name
	attributeDefaults[attributeKeys.CUSTOMER_NAME_FONT] = 'Helvetica;46px;normal;normal';
	

	// 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),
				
				topMargin = attribParser.getString(attributeKeys.TICKET_TOP_MARGIN, attributeDefaults[attributeKeys.TICKET_TOP_MARGIN]) + 'px',
				
				ticketBackgroundColor = attribParser.getString(attributeKeys.TICKET_BACKGROUND_COLOR, attributeDefaults[attributeKeys.TICKET_BACKGROUND_COLOR]),
				ticketBackgroundTransparency = attribParser.getString(attributeKeys.TICKET_BACKGROUND_TRANSPARENCY, attributeDefaults[attributeKeys.TICKET_BACKGROUND_TRANSPARENCY]),
				ticketNumberColor = attribParser.getString(attributeKeys.TICKET_NUMBER_COLOR, attributeDefaults[attributeKeys.TICKET_NUMBER_COLOR]),
				ticketNumberFontSize = attribParser.getFontSize(attributeKeys.TICKET_NUMBER_FONT, defaultsParser.getFontSize(attributeKeys.TICKET_NUMBER_FONT)),
				ticketNumberFontFamily = attribParser.getFontFamily(attributeKeys.TICKET_NUMBER_FONT, defaultsParser.getFontFamily(attributeKeys.TICKET_NUMBER_FONT)),
				ticketNumberFontStyle = attribParser.getFontStyle(attributeKeys.TICKET_NUMBER_FONT, defaultsParser.getFontStyle(attributeKeys.TICKET_NUMBER_FONT)),
				ticketNumberFontWeight = attribParser.getFontWeight(attributeKeys.TICKET_NUMBER_FONT, defaultsParser.getFontWeight(attributeKeys.TICKET_NUMBER_FONT)),
				ticketStationColor = attribParser.getString(attributeKeys.TICKET_STATION_COLOR, attributeDefaults[attributeKeys.TICKET_STATION_COLOR]),
				ticketStationFontSize = attribParser.getFontSize(attributeKeys.TICKET_STATION_FONT, defaultsParser.getFontSize(attributeKeys.TICKET_STATION_FONT)),
				ticketStationFontFamily = attribParser.getFontFamily(attributeKeys.TICKET_STATION_FONT, defaultsParser.getFontFamily(attributeKeys.TICKET_STATION_FONT)),
				ticketStationFontStyle = attribParser.getFontStyle(attributeKeys.TICKET_STATION_FONT, defaultsParser.getFontStyle(attributeKeys.TICKET_STATION_FONT)),
				ticketStationFontWeight = attribParser.getFontWeight(attributeKeys.TICKET_STATION_FONT, defaultsParser.getFontWeight(attributeKeys.TICKET_STATION_FONT));

			globalFlashDuration = attribParser.getInteger(attributeKeys.TICKET_FLASH_DURATION, attributeDefaults[attributeKeys.TICKET_FLASH_DURATION]);
			globalTicketTextColor = attribParser.getString(attributeKeys.TICKET_TEXT_COLOR, attributeDefaults[attributeKeys.TICKET_TEXT_COLOR]);
            globalTicketTextFontFamily = attribParser.getFontFamily(attributeKeys.TICKET_TEXT_FONT, attributeDefaults[attributeKeys.TICKET_TEXT_FONT]);
            globalTicketTextFontSize = attribParser.getFontSize(attributeKeys.TICKET_TEXT_FONT, attributeDefaults[attributeKeys.TICKET_TEXT_FONT]);
            globalTicketTextFontStyle = attribParser.getFontStyle(attributeKeys.TICKET_TEXT_FONT, defaultsParser.getFontStyle(attributeKeys.TICKET_TEXT_FONT));
            globalTicketTextFontWeight = attribParser.getFontWeight(attributeKeys.TICKET_TEXT_FONT, defaultsParser.getFontWeight(attributeKeys.TICKET_TEXT_FONT));
            globalTicketText = attribParser.getString(attributeKeys.TICKET_TEXT, attributeDefaults[attributeKeys.TICKET_TEXT]);
            globalCounterText = attribParser.getString(attributeKeys.COUNTER_TEXT, attributeDefaults[attributeKeys.COUNTER_TEXT]);
			globalShowDirection = attribParser.getBoolean(attributeKeys.TICKET_SHOW_DIRECTION, attributeDefaults[attributeKeys.TICKET_SHOW_DIRECTION]);
			globalShowFrame = attribParser.getBoolean(attributeKeys.SHOW_FRAME, attributeDefaults[attributeKeys.SHOW_FRAME]);
			globalFrameRadius = attribParser.getInteger(attributeKeys.FRAME_RADIUS, attributeDefaults[attributeKeys.FRAME_RADIUS]);
			globalFlashSpeed = attribParser.getInteger(attributeKeys.FLASH_SPEED, attributeDefaults[attributeKeys.FLASH_SPEED]);

		  globalShowCustomerName = attribParser.getInteger(attributeKeys.SHOW_CUSTOMER_NAME, attributeDefaults[attributeKeys.SHOW_CUSTOMER_NAME]);
			globalCustomerNameFontSize = attribParser.getFontSize(attributeKeys.CUSTOMER_NAME_FONT, defaultsParser.getFontSize(attributeKeys.CUSTOMER_NAME_FONT));
			globalCustomerNameFontFamily = attribParser.getFontFamily(attributeKeys.CUSTOMER_NAME_FONT, defaultsParser.getFontFamily(attributeKeys.CUSTOMER_NAME_FONT));
			globalCustomerNameFontStyle = attribParser.getFontStyle(attributeKeys.CUSTOMER_NAME_FONT, defaultsParser.getFontStyle(attributeKeys.CUSTOMER_NAME_FONT));
			globalCustomerNameFontWeight = attribParser.getFontWeight(attributeKeys.CUSTOMER_NAME_FONT, defaultsParser.getFontWeight(attributeKeys.CUSTOMER_NAME_FONT));
			
			if(globalShowDirection) {
				globalLeftArrow = attribParser.getImageUrl(attributeKeys.TICKET_LEFT_ARROW, attributeDefaults[attributeKeys.TICKET_LEFT_ARROW]);
				globalRightArrow = attribParser.getImageUrl(attributeKeys.TICKET_RIGHT_ARROW, attributeDefaults[attributeKeys.TICKET_RIGHT_ARROW]);
			}
			
			useSpName = attribParser.getBoolean(attributeKeys.USE_SP_NAME, false);

      var c = ticketBackgroundColor.replace('#', '');
      if(c.length == 6 & ticketBackgroundTransparency !== undefined) {
        if(ticketBackgroundTransparency > 100) { ticketBackgroundTransparency = 100; }
        if(ticketBackgroundTransparency < 0) { ticketBackgroundTransparency = 0; }
        ticketBackgroundColor = 'rgba(' + parseInt(c.substring(0,2),16) + ',' + parseInt(c.substring(2,4),16) + ',' + parseInt(c.substring(4,6),16) + ',' + (ticketBackgroundTransparency/100) + ')';
      }
			
			attributes = attr;
			ticketCall = new qmatic.Callwidget({
				id						: 'ticketCall'
			});
			
			ticketCall.onBeforeShowEntry = function(entryElem, isCustomerName) {
				var numberElem,
					stationElem;
				
				if (typeof entryElem !== 'undefined' && entryElem != null) {
					entryElem.find('.ticketEntry').css('background', ticketBackgroundColor);
					if(globalShowFrame){
						entryElem.find('.ticketEntry').css('box-shadow', '3px 2px 2px #C3C3C3');
					}
					entryElem.find('.ticketEntry').css('border-radius', globalFrameRadius + 'px');
					entryElem.find('#ticketDimensions').css('margin-top', topMargin);
          entryElem.find('.text_element').css('color', globalTicketTextColor)
              .css('font-size', globalTicketTextFontSize).css('font-family', globalTicketTextFontFamily)
              .css('font-style', globalTicketTextFontStyle).css('font-weight', globalTicketTextFontWeight);
					
					numberElem = entryElem.find('.ticketNumberStyle');
					
					if(isCustomerName) {
  					numberElem.css('color', ticketNumberColor).css('font-size', globalCustomerNameFontSize)
  						.css('font-family', globalCustomerNameFontFamily).css('font-style', globalCustomerNameFontStyle)
  						.css('font-weight', globalCustomerNameFontWeight);
          } else {
  					numberElem.css('color', ticketNumberColor).css('font-size', ticketNumberFontSize)
  						.css('font-family', ticketNumberFontFamily).css('font-style', ticketNumberFontStyle)
  						.css('font-weight', ticketNumberFontWeight);
          }

					stationElem = entryElem.find('.stationNameStyle');
					stationElem.css('font-size', ticketStationFontSize).css('font-family', ticketStationFontFamily)
						.css('color', ticketStationColor).css('font-style', ticketStationFontStyle)
						.css('font-weight', ticketStationFontWeight);
					
				}
			};

			// We listen for customer ticket call event which is triggered whenever a workstation calls for the next
			// customer waiting in queue. 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') {
				// Note that you shouldn't use this widget in positional displays, use the "Positional Display Call Widget" instead.
				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);