﻿/**
 * Satisfaction index
 */
function satisfaction_index() {
	
	/**
	 * Reference to the satisfaction_index object
	 *
	 * @access private
	 */
	var si_obj = this;
	
	/**
	 *
	 * @access public
	 */
	this.init = function() {

		// Find all satisfaction indexes by class
		$('.satisfaction_index').each(function() {
			init_si(this);		
		});
	}

	
	/**
	 * Initiate si
	 * 
	 * @access private
	 * @param object	reference to si <div> tag
	 */
	function init_si(si)
	{
		// Get width from html
		var width = $(si)
		.find('div.width').html();
		
		// Set width
		$(si)
		.find('div.sort')
			.css('width', width + 'px');
		
		// Make sortabale
		$(si)
		.find('div.sortable')
			.sortable();
		
		// bind funciton to the button
		$(si)
		.find('button')
			.click(function() {
				// Bind a mthod of the satisfactioni_index object
				si_obj.add_input_fields(si);
			});
	}

	
	/**
	 * Add input fields to the top four qualities. The last two qualities are removed from the DOM.
	 * This function is fired after the user sorts the list.
	 *
	 * @access public
	 * @param object	refference to the satisfaction index <div> tag
	 */
	this.add_input_fields = function(si) {
		
		// Get html
		var html = $(si).html();
		
		// remove the 'sortable' class from the div
		html = html.replace(/sortable/, '');
		
		// Create a div with the original html
		$(si).append('<div class="original_html">' + html + '</div>');
		
		// Get width from html and add 5 (px)
		var width = $(si)
			.find('div.width').html() * 1 + 5;
	
		$(si)
		// Make list not sortable
		.find('div.sortable').sortable('destroy')
		    .children()
			// Add input fields to the first four nodes, delete the rest
			.each(function (i) {
				// If one of the first four nodes
				if (i<4)
				{
					$(this)
					.find('> div')
						.after('<input type="text" value="5" maxlength="2" style="left:' + width +'px" />');
				}
				else
				{
					//$(this).remove();
					$(this).hide();
				}
			})
			.end()
			.end()
		// Remove button
		.find('> button')
			.remove()
			.end()
		// Add a new button 
		.find('div.sortable')
			.after('<button class="button">' + lang_show_results + '</button>')
			.end()
		.find('button')
			.click(function() {
				
				// Bind a method of the satisfaction_index object
				si_obj.calculate(si);
			});
	};
	
	/**
	 * Calculates the results. Calculates the percent, determines the critical keywords.
	 *
	 * @access public
	 * @param object	refference to the satisfaction index <div> tag
	 */
	this.calculate = function(obj) {
	
		// The percentage that is to be calculated
		var percent = 0;
		
		// The primary word that is to be calculated
		var calculated_primary;
		
		// The critical keywords, that are associated with the calculated primary word
		var critical_keywords = [];
		
		/*
		* Type of results to show. This value is taken from the satsifaction index html
		* Allowed values are:
		*	'only_percentage'
		*	'with_keywords'
		* 	'with_keywords_and_primary' 
		*/
		var result_type = '';
		
		/*
		 * These objects represent the top four qualities. 
		 * The following information will be stored in these objects:
		 *	object.input 		- the value that the user inputed
		 *	object.calculated	- the value that was calculated
		 *	object.percent		- the value that was calculated for the percentage
		 *	object.primary_word	- the primary word that is associated with that quality
		 */
		var a = {};
		var b = {};
		var c = {};
		var d = {};
		
		// Is the inputed data valid? Default true.
		var valid_fields = true;
		
		// Go through all the input fields
		$(obj)
			.find('div.sortable')
			.find('input')
			
			// Get a,b,c,d
			.each(function (i) {
				
				// Get value and convert it to integer
				var value = this.value * 1;
				
				// If value is not a number from 1 to 10
				if ( ! (value > 0 && value <=10))
				{
					// Add error class to the input field
					$(this).addClass('error')
						// When user will focus on this field the error class will be removed
						.focus(function() {
							$(this).removeClass('error');
						});
					// Skip to the next iteration (next input)
					valid_fields = false;
					return true;
				}
				
				// If first quality
				if (i==0) 
				{ 
					a['input'] = value * 1;
					a['calculated'] = (10 - a['input']) * 4;
					a['percent'] = a['input'] * 4;
					a['primary_word'] = $(this).parent().find('span.primary_keyword').html();
					
				}
				// If second quality
				if (i==1) 
				{ 
					b['input'] = value * 1;
					b['calculated'] = (10 - b['input']) * 3;
					b['percent'] = b['input'] * 3;
					b['primary_word'] = $(this).parent().find('span.primary_keyword').html();
					
				}
				if (i==2) 
				{ 
					c['input'] = value * 1;
					c['calculated'] = (10 - c['input']) * 2;
					c['percent'] = c['input'] * 2;
					c['primary_word'] = $(this).parent().find('span.primary_keyword').html();
					
				}
				if (i==3) 
				{ 
					d['input'] = value * 1;
					d['calculated'] = (10 - d['input']) * 1;
					d['percent'] = d['input'];
					d['primary_word'] = $(this).parent().find('span.primary_keyword').html();
				}
				
			});
			
		if( ! valid_fields)
		{
			return;
		}
		else if (a['input'] == 5 && b['input'] == 5 && c['input'] == 5 && d['input'] == 5)
		{
			alert('Please enter scores in the boxes');
			$(obj).find('input:first').focus().select();
			return;
		}
		
		// debug
		//a['calculated'] = 18;
		//b['calculated'] = 2;
		//c['calculated'] = 3;
		//d['calculated'] = 10;
		
		/*
		 * Determine which is the quality that can be most improved
		 */
		if (a['calculated'] >= b['calculated'])
		{
			if (a['calculated'] >= c['calculated'])
			{
				if (a['calculated'] >= d['calculated'])
				{
					calculated_primary = a['primary_word'];
					//alert('a');
				}
				else
				{
					calculated_primary = d['primary_word']; 
					//alert('d');
				}
			}
			else
			{
				if (c['calculated'] >= d['calculated'])
				{
					calculated_primary = c['primary_word']; 
					//alert('c');
				}
				else
				{
					calculated_primary = d['primary_word']; 
					//alert('d');
				}
			}
		}
		else
		{
			if (b['calculated'] >= c['calculated'])
			{
				if (b['calculated'] >= d['calculated'])
				{
					calculated_primary = b['primary_word'];
					//alert('b');
				}
				else
				{
					calculated_primary = d['primary_word']; 
					//alert('d');
				}
			}
			else
			{
				if (c['calculated'] >= d['calculated'])
				{
					calculated_primary = c['primary_word']; 
					//alert('c');
				}
				else
				{
					calculated_primary = d['primary_word']; 
					//alert('d');
				}
			}
		}
		
		// debug
		//var msg = 'inputed values: ' + a['input'] + ' ' + b['input'] + ' ' + c['input'] + ' ' + d['input'];
		//msg += ' \ncalculated values:' + a['calculated'] + ' ' + b['calculated'] + ' ' + c['calculated'] + ' ' + d['calculated'] + ' ';
		//alert(msg);
		
		// Critical keywords
		critical_keywords = keywords[calculated_primary];
		
		// Percent
		percent = a['percent']+b['percent']+c['percent']+d['percent'];
		
		// Get resutl type from <ul> class attribute
		result_type = $(obj).find('div.result_type').html();
		
		// Get si name from html
		si_name = $(obj).find('div.name').html();
		
		/* Do statistics */
		
		// Get the list of qualities that user has sorted
		var user_list = [];
		
		$(obj)
			.find('> div div.sort > div')
				.each(function(i) {
					user_list[i] = $(this).html();
				});
				
		// Get the inputed values
		var user_input = [ a['input'], b['input'], c['input'], d['input'] ];
		
		$.ajax({
		  dataType: 'jsonp',
		  data: { 
				name: si_name,
				percent: percent,
				'user_list[]'	: user_list,
				'user_input[]'	: user_input
		  },
		  url: statistics_url
		});
		
		// Show results
		show_result(obj, result_type, percent, critical_keywords, calculated_primary);
	};
	
	/**
	 * Shows the result
	 *
	 * @access private
	 * @param object	refference to the satisfaction index <div> tag
	 * @param string	results type
	 * @param integer	percentage
	 */
	function show_result(obj, type, percent, critical_keywords, primary_keyword) {
		
		var result_html = results_only_percent;
		
		switch (type)
		{
			case 'with_keywords':
				result_html = results_with_keywords;
				break;
			case 'with_keywords_and_primary':
				result_html = results_with_keywords_and_primary;
				break;
		}
		
		result_html = result_html.replace(/\{percent\}/, percent);
		
		// If result with keywords
		if (type == 'with_keywords' || type == 'with_keywords_and_primary')
		{
			var counter = 0;
			var pattern = '';
			for (var i in critical_keywords)
			{
				counter++;
				pattern = '\{keyword' + counter +'\}';
				var regex = new RegExp(pattern)
				result_html = result_html.replace(regex, critical_keywords[i]);
			}
		}

		// If result with primary keyword
		if (type == 'with_keywords_and_primary')
		{
			result_html = result_html.replace(/\{primary_keyword\}/, primary_keyword);
		}
				
		$(obj).hide();
		
		$(obj)
		// Get all html exept the div with the original html
		.find('> *')
			.not('div.original_html')
				.remove()
				.end()
			.end()
		// Prepend the results html
		.prepend(result_html)
		.fadeIn('slow')
		// Add click event to the button witch resets the satisfaction index
		.find('button')
			.click(function () {
			
				// Hide
				$(obj)
				.css('display', 'none');
				
				// Get the original html
				var original_html = $(obj).find('div.original_html').html();
				
				// Restore the original html
				$(obj)
				.html(original_html)
				.find('.ui-sortable')
					.addClass('sortable')
					.removeClass('ui-sortable')
					.end()
				.fadeIn('slow');
				
				// Initiate the restored satisfaction index html
				init_si(obj);
			});
	}
	
} // end of Satisfaction index object

// Create satisfaction index object
var satisfaction_index_obj = new satisfaction_index();

// When the DOM is ready
$(document).ready(function(){
		
	// Initiate the satisfaction indexes
	satisfaction_index_obj.init();
});