// com.tts.initial.html5.quiz.result.overall.v2
define(["jquery"],function( jq ) {
	"use strict";

	/**
	 * @constructor
	 */
	function ScoreOverall( context, metadata ) {

		// declare private members
		var scoreBar = null,
			scoreTextBox = null,

			allQuestions = context.quiz.getQuestions(),
			allPages = metadata.stage.pages,

			parameters = metadata.parameters,

			borderColor = asRgbaValue( "borderColor", "#98a7b5", "borderTransparency" ),
			backgroundColor = asRgbaValue( "backgroundColor", "#d8dee3", "backgroundTransparency" ),
			barColor = asRgbaValue( "barColor", "#95b3d7", "barTransparency" ),

			borderSize = parameters.asNumber( "borderSize", 1 ),
			showLabels = parameters.asNumber( "hideLabels", 0 ) !== 1,
			minLabelWidth = 25,
			maxLabelWidth = 40,

			displayAs = parameters.asNumber( "displayAs", "0" ),
			fontSize = parameters.asNumber( "fontSize", "16" ),
			fontFamily = parameters.asNumber( "fontFamily", "Arial, Helvetica, sans - serif" ),
			textColor = parameters.get( "textColor", "#142534" ),
			textOrientation = parameters.get( "textOrientation", "left" ),
			paddingLeft = parameters.asNumber( "paddingLeft", "10" ),
			paddingRight = parameters.asNumber( "paddingRight", "10" ),
			paddingTop = parameters.asNumber( "paddingTop", "12" );

		function asRgbaValue( colorParameterName, defaultColor, transparencyParameterName ) {

			var color = hexToRgb( parameters.get(colorParameterName, defaultColor)),
				alpha = asAlpha( parameters.asNumber(transparencyParameterName, 0) );

			return "rgba(" + color.r + ", " + color.g + ", " + color.b + ", " + alpha + ")";
		}

		function hexToRgb( hex ) {
			var parsingResult = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);

			return parsingResult ? {
				r: parseInt(parsingResult[1], 16),
				g: parseInt(parsingResult[2], 16),
				b: parseInt(parsingResult[3], 16)
			} : {
				r: 0,
				g: 0,
				b: 0
			};
		}

		function asAlpha( percentValue ) {
			return (100 - percentValue) / 100;
		}

		function getFontFamilyString( fontFamily ) {
			switch ( parseInt( fontFamily ) ) {
				case 2:
					return "'Times New Roman', Times, serif";
				case 3:
					return "Verdana, Geneva, sans-serif";
				case 4:
					return "'Courier New', Courier, monospace";
				case 1:
				default:
			}
			return "Arial, Helvetica, sans-serif";
		}

		function getQuestion( page ) {
			for ( var i = 0; i < allQuestions.length; i++ ) {
				if ( page.getId() === allQuestions[i].getPageMetadata().getId() ) {
					return allQuestions[i];
				}
			}
			return null;
		}

		function getQuestionResultObject( question ) {
			var userScore = parseInt( question.getScore() ),
				maxScore = parseInt( question.getMaxScore() );

			return {
				userScore: userScore,
				maxScore: maxScore
			}
		}

		function createView() {
			if ( displayAs == 0 ) {
				createBarView();
			} else {
				createTextView();
            }
		}

		function createTextView() {
			var shellElement = jq( context.getElement() );

			scoreTextBox = jq( document.createElement( "div" ) )
				.html( "[...]" )
				.css( {
					"width": "100%",
					"height": "100%",
					"background-color": backgroundColor,
					"font-family": getFontFamilyString( fontFamily ),
					"font-size": fontSize + "px",
					"color": textColor,
					"line-height": fontSize + "px",
					"padding-left": ( paddingLeft - borderSize ) + "px",
					"padding-right": ( paddingRight - borderSize ) + "px",
					"padding-top": ( paddingTop - borderSize ) + "px",
					"text-align": textOrientation,
					"box-sizing": "border-box"
				} );

			

			if ( borderSize !== 0 ) {
				scoreTextBox.css( "border", borderSize + "px solid " + borderColor );
			}

			shellElement.append( scoreTextBox );

			if ( context.stage.isInAuthoringMode() ) {
				createAuthoringShield( shellElement );
			}
		}

		function createBarView() {
			var shellElement = jq(context.getElement())
				.css({
					"font-family": "Arial, Helvetica, sans-serif",
					"font-size": "12px",
					"padding": "0",
					"margin": "0",
					"border": "0"
				})
				.append( createProgressBarTable() );

			if (context.stage.isInAuthoringMode()) {
				createAuthoringShield(shellElement);
			}
		}

		function createProgressBarTable(){
			return jq(document.createElement("table"))
				.css({
					"position": "absolute",
					"padding": "0",
					"margin": "0",
					"border": "0",
					"width": "100%",
					"height": "100%",
					"border-collapse": "collapse",
					"border-spacing": "0px"
				})
				.append( createTableBody() );
		}

		function createTableBody() {
			return jq( document.createElement( "tbody" ) )
				.css( {
					"padding": "0",
					"margin": "0",
					"border": "0"
                })
				.append( createTableRow() );
		}

		function createTableRow(){

			var tableRow = jq( document.createElement( "tr" ) )
					.css( {
						"padding": "0",
						"margin": "0",
						"border": "0"
					} ),
				width = metadata.getWidth() - (2 * borderSize);

			if (showLabels) {
				tableRow.append( createMinLabelCell() );
				tableRow.append( createProgressBarCell( width - minLabelWidth - maxLabelWidth ) );
				tableRow.append( createMaxLabelCell() );
			}
			else {
				tableRow.append( createProgressBarCell( width ) );
			}

			return tableRow;
		}

		function createMinLabelCell(){
			return jq(document.createElement("td"))
				.css( {
					"height": "100%",
					"width": minLabelWidth + "px",
					"padding": "0",
					"margin": "0",
					"border": "0"
				})
				.text("0%");
		}

		function createProgressBarCell( width ){
			return jq(document.createElement("td"))
				.css({
					"height": "100%"
				})
				.append( createBackgroundBar( width ) );
		}

		function createBackgroundBar( width ){

			scoreBar = createScoreBar();

			return jq(document.createElement("div"))
				.css({
					"width": "100%",
					"height": "100%",
					"border": borderSize + "px solid " + borderColor,
					"background-color": backgroundColor,
					"box-sizing": "border-box"
				})
				.append( scoreBar );
		}

		function createScoreBar() {
			return jq(document.createElement("div"))
				.width(context.stage.isInAuthoringMode() ? "50%" : "0")
				.css({
					"height": "100%",
					"background-color": barColor
				})
		}

		function createMaxLabelCell(){
			return jq(document.createElement("td"))
				.css( {
					"height": "100%",
					"text-align": "right",
					"width": maxLabelWidth + "px"
				})
				.text("100%");
		}

		function createAuthoringShield( shellElement ) {
			// create an object shield so we are able to select and drag the element in the editor
			shellElement.append( jq( document.createElement( "div" ) )
				.css( {
					"position": "absolute",
					"left": 0,
					"top": 0,
					"background-color": "transparent",
					"opacity": "0.4",
					"width": "100%",
					"height": "100%",
					"z-index": "9999"
				} ) );
		}

		function refreshView() {
			if ( displayAs == 0 ) {
				if ( !context.stage.isInAuthoringMode() ) {
					scoreBar.width( parseInt( context.quiz.getScore() ) + "%" );
				}
			} else {
				var allQuizPages = allPages.filter( function ( page ) {
						return getQuestion( page ) !== null;
					} ),
					achievedPoints = 0,
					achievablePoints = 0,
					percentageAchievedPoints = Math.round( context.quiz.getScore() ),
					percentageMasteryScore = context.quiz.getMasteryScore(),
					masteryScorePoints = 0,
					value;

				for ( var i = 0; i < allQuizPages.length; i++ ) {
					var question = getQuestion( allQuizPages[i] ),
						questionResult = getQuestionResultObject( question );

					achievablePoints = achievablePoints + questionResult.maxScore;
					achievedPoints = achievedPoints + questionResult.userScore;
				}

				masteryScorePoints = Math.round( achievablePoints * ( percentageMasteryScore / 100 ) );

				switch ( displayAs ) {
					case 1:
						value = achievedPoints;
						break;
					case 2:
						value = achievablePoints;
						break;
					case 3:
						value = percentageAchievedPoints;
						break;
					case 4:
						value = percentageMasteryScore;
						break;
					case 5:
						value = masteryScorePoints;
						break;
					default:
						value = achievedPoints;
				}

				scoreTextBox.html( value );
            }
		}

		// revealing public API
		return {

			onLoading : function() {

				context.page.event.bindOnEnter( this );

				if( typeof( context.page.event.bindOnTransform ) === "function" ) {
					context.page.event.bindOnTransform( this );
				}

				createView();
			},

			onEnterPage : function() {
				refreshView();
			},

			onTransformPageStart : function() {
				refreshView();
			}
		};
	}

	return ScoreOverall;
});
