/* ------------------------
Assessment processing functions

These functions capture assessment data and produce
the final results email for transmission back to the
integrtion server.

Copyright Demodia GmbH 2009
 - all rights reserved -
------------------------ */

var gSelectedTab = 0;  // id of currently selected tab
var gTempTab = 0;
var demBenchmarks = [6,5,5,6,4,5];


$(document).ready(function(){

	// hide tabs which aren't used till later
    $('#tabs').hide();
    $('#tabs-warning').hide();
    $('#divcon').hide();
    $('.chartcontainer').hide();
    
    // setup Eloqua tracking links
    $('a.elq-link').makeEloquaLink();
    
    				
	// initiate tabs panel    
    var tabs = $('#tabs').tabs({
        select: function(event, ui) {
            var isValid = false;
            
           if ( ui.panel.id == $('.tab-panel:last').attr("id") && !checkAllComplete() ){
				gTempTab = ui.index;
				$('.tab-panel').hide();
				$('#tabs-warning').show();

            }
            else if ( ui.panel.id == $('.tab-panel:last').attr("id") && checkAllComplete() ){
				gSelectedTab = ui.index;
				showResults();
				isValid = true;
           }
			else {
				if( gSelectedTab != ui.index ){
                    if( gSelectedTab == 0 || checkComplete() ){
						gSelectedTab = ui.index;
						isValid = true;
					}
					else {
						gTempTab = ui.index;
						$('.tab-panel').hide();
						$('#tabs-warning').show();
                    }
                }
                else
                	isValid = true;
            }
            return isValid;
        }
    });
    
    gSelectedTab = tabs.tabs('option', 'selected');

	// initialise the warning panel - displayed when users try and click out of sequence.
    $('.to-warning').click(function() { // bind click event to link
    	if( $(this).attr("action") == "continue"){
			gSelectedTab = gTempTab;
			tabs.tabs('select', gTempTab);
    	}
    	else if( $(this).attr("action") == "back"){
			tabs.tabs('select', gSelectedTab);
    	}
		$('.tab-panel').show();
		$('#tabs-warning').hide();
    });	

	// initialise the "Show Assesment" button on the front page
    $('.show-assessment').click(function() { // bind click event to link
		$('#tabs').show( 'blind', 'slow' );
		$('.show-assessment').fadeOut();
    });
    
    // actions performed when clicking on the "next" button within assessment tabs
    $('.to-tab').click(function() { // bind click event to link
        if( $(this).attr("action") == "submit_results" ){
			$('#assessment-form').submit();
        }
		else if( $(this).attr("action") == "next" && checkComplete() && $('#chart'+ gSelectedTab +'container:hidden').length >= 1){
			disableOptions();
			showSummary();
        }
        else {
        	if( $(this).attr("action") == "next"){
        		tabs.tabs('select', new Number($(this).attr("tab"))+1 );
        	}
        	else if( $(this).attr("action") == "back"){
        		tabs.tabs('select', new Number($(this).attr("tab"))-1 );
        	}
		}
        return false;
    });

	// set-up assessment incomplete dialogue
	$('#result-dialog').dialog({
        dialogClass: 'alert',
		modal: true,
		autoOpen: false,
		buttons: {
			"Cancel": function() {
				tabs.tabs('select', gSelectedTab);
				$(this).dialog("close"); 
			},
			"Continue": function() {
				gSelectedTab = gTempTab;
				$(this).dialog("close"); 
			}
		}
	});
	
	// capture form submit events and pre-process data before sending
//	$("#assessment-form").submit( submitPre );
	$("#assessment-form").validate({
		submitHandler: function(form) {
			if( submitPre() )
				form.submit();
		}
	});

});

// submitPre()
//
// verifies that the user has completed all the questions within the current tab.

function submitPre(){
	enableAllOptions();
	$("#demResultMessage").attr("value", $("#result-panel-content").html());
	$("input:radio").setAnswer();
	
	var elqQueryString = $('#assessment-form .elqfield').fieldSerialize();
	var queryString = $('#assessment-form .postfield').fieldSerialize();
	$('#elqfields').val( elqQueryString );
	return true;
}


// checkComplete()
//
// verifies that the user has completed all the questions within the current tab.

function checkComplete(){
	var current_tab = "#tabs-" + (gSelectedTab);
	var num_questions = $(current_tab +" .question").length;
	var num_answers =  $(current_tab+" input:radio:checked").length;
	if( num_questions != num_answers)
		return false;
	else
		return true;
}

// checkAllComplete()
//
// verifies that the user has completed all the questions within the whole survey.

function checkAllComplete(){
	var num_questions = $("td.question").length;
	var num_answers =  $("input:radio:checked").length;
	if( num_questions != num_answers)
		return false;
	else
		return true;
}

// makeEloquaLink
//
// Adds Eloqua tracking to URLs

jQuery.fn.makeEloquaLink = function() {
	this.each(function(){
		var elqID = jQuery.url.param("elq");
		var url = $(this).attr("href");
		var elq_url = url.replace( /elq=/, "elq="+elqID );
    	$(this).attr("href", elq_url) ;
	});
};



// showSummary()
//
// calculates and displays summary results for current tab

function showSummary(){
	var current_tab = "#tabs-" + (gSelectedTab);
	var num_questions = $(current_tab+" td.question").length;
	$(current_tab+" input:radio").setScore();
	var total_answers =  $(current_tab+" input:radio:checked").sum();
	var percentage_val = ( total_answers / (num_questions * 2)) * 100;
	var chart = new FusionCharts("http://www2.demodia.com/charts/HLinearGauge.swf", "chart"+ (gSelectedTab) +"Id", "450", "75", "0", "1");		   			
	chart.setDataXML("<Chart bgColor='FEEFD1' baseFontColor='FFFFFF' baseFontSize='14' bgAlpha='100' showLimits='0' showBorder='0' borderColor='FEEFD1' borderAlpha='100' upperLimit='100' lowerLimit='0' showValue='0' gaugeRoundRadius='5' chartTopMargin='10' chartBottomMargin='10' chartLeftMargin='10' ticksBelowGauge='0' showTickMarks='0' showGaugeLabels='1' valueAbovePointer='0' pointerOnTop='1' pointerRadius='9'><colorRange><color minValue='0' maxValue='35' code='FF654F' label='Just Starting'/><color minValue='35' maxValue='85' code='F6BD0F' label='Work Required'/><color minValue='85' maxValue='100' code='8BBA00' label='Ready'/></colorRange><value>"+ percentage_val +"</value><styles><definition><style name='ValueFont' type='Font' bgColor='333333' size='10' color='FFFFFF'/></definition><application><apply toObject='VALUE' styles='valueFont'/></application></styles></Chart>");
	chart.render("chart"+ (gSelectedTab) +"div");
	$('#chart'+ (gSelectedTab) +'container').show();
}

// showResults()
//
// calculates and displays final results page, also set up content for results email.

function showResults(){
	$("input:radio").setScore();
	var total_score =  $("input:radio:checked").sum();
	var total_questions = $("td.question").length;
	$("#rating").html( total_score + " / " +(total_questions *2));
	$("#rating2").html( total_score + " / " +(total_questions *2));
	
	for(var i=1; i<($('#tabs').tabs('length')-1);i++ ){ // want to miss first and last tabs out
		var current_tab = "#tabs-" + i;
		var num_questions = $(current_tab+" td.question").length;
		var total_answers =  $(current_tab+" input:radio:checked").sum();
		var percentage_val = ( total_answers / (num_questions * 2)) * 100;
		
		$("#demTab"+i).val( total_answers );
		
		if( percentage_val < percentage_low ){
			$("#comment"+i).html( eval( "tab"+i+"_low" ) );
		}
		else if( percentage_val < percentage_med ){
			$("#comment"+i).html( eval( "tab"+i+"_med" ) );					
		}
		else {
			$("#comment"+i).html( eval( "tab"+i+"_high" ) );
		}
		
	} 
	
	var chart = new FusionCharts("http://www2.demodia.com/charts/Radar.swf", "radarchartId", "450", "350", "0", "1");
	
	chart.setDataXML("<chart yAxisMaxValue='8' showToolTip='0' showLegend='1' anchorAlpha='0'><categories><category label='Environment' /><category label='Interoperability' /><category label='Compliance' /><category label='Scalability' /><category label='Productivity' /><category label='Security' /></categories><dataset seriesName='Benchmark Results'><set value='"+demBenchmarks[0]+"' /><set value='"+demBenchmarks[1]+"' /><set value='"+demBenchmarks[2]+"' /><set value='"+demBenchmarks[3]+"' /><set value='"+demBenchmarks[4]+"' /><set value='"+demBenchmarks[5]+"' /></dataset><dataset seriesName='My Results'><set value='"+$('#tabs-1 input:radio:checked').sum() +"' /><set value='"+$('#tabs-2 input:radio:checked').sum() +"' /><set value='"+$('#tabs-3 input:radio:checked').sum() +"' /><set value='"+$('#tabs-4 input:radio:checked').sum() +"' /><set value='"+$('#tabs-5 input:radio:checked').sum() +"' /><set value='"+$('#tabs-6 input:radio:checked').sum() +"' /></dataset></chart>");
	
	chart.render("radarchart");

}

// disableOptions()
//
// disables all checkboxes within the currently selected tab.

function disableOptions(){
	var current_tab = "#tabs-" + (gSelectedTab);
	$(current_tab+" input:radio").each(function(i){$(this).attr("disabled", true)});
}

// disableOptions()
//
// disables all checkboxes within the currently selected tab.

function enableAllOptions(){
	var current_tab = "#tabs-" + (gSelectedTab);
	$("input:radio").each(function(i){$(this).attr("disabled", false)});
}

// setAnswer()
//
// supporting function to set value of an input
// field equal to its "answer" attribute.

jQuery.fn.setAnswer = function() {
	this.each(function(){
	    $(this).attr("value", $(this).attr("answer")) ;
	});
};

// setScore()
//
// supporting function to set value of an input
// field equal to its "score" attribute.

jQuery.fn.setScore = function() {
	this.each(function(){
	    $(this).attr("value", $(this).attr("score")) ;
	});
};
