/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function urlencode( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir
    // %          note: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
                             
    var histogram = {}, tmp_arr = [];
    var ret = str.toString();
    
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
    
    // The histogram is identical to the one in urldecode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions
    ret = encodeURIComponent(ret);
    
    for (search in histogram) {
        replace = histogram[search];
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }
    
    // Uppercase for full PHP compatibility
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
        return "%"+m2.toUpperCase();
    });
    
    return ret;
}

function askfirst(text, url)
{
	var answer = confirm (text);
	
	if (answer)
		window.location=url;
}

//provide a random timestamp with each call to foil caching
function getTimestamp()
{
	var t = new Date();
	var r = "" + t.getFullYear() + t.getMonth() + t.getDate() + t.getHours() + t.getMinutes() + t.getSeconds(); 

	return(r);
}

var ssass_min;
var ssass_max;
var ssass_questions = new Array();
var ssass_weights = new Array();
var ssass_ratings = new Array();
var ssass_total;

function rateQuestion(r, q)
{
	//update the rating box
	$('current_rating_'+q).style.width = (r * 18) + 'px';
	
	//update the hidden value
	$('qv_'+q).value = r;	
	
	//update the var
	ssass_ratings[q] = r;		

	calculateAssessment();
}

function calculateAssessment()
{
	//update the total		
	var ssass_score = 0;
	var ssass_range = Math.abs(ssass_max - ssass_min);
	ssass_questions.each(function(q) {
		ssass_score = ssass_score + (ssass_weights[q] * ssass_ratings[q]);		
	});	
	ssass_total = Math.round(((ssass_score - ssass_min)/ssass_range)*100);
	$('assessment_total').innerHTML = ssass_total + '%';
	$('ssass_total').value = ssass_total + '%';
}

function loadAssessment(a, r)
{
	var url = '/wp-content/plugins/ssassessments/services/showassessment.php';
	var pars = 'a=' + a + '&r=' + r + '&ts=' + getTimestamp();
	var myAjax = new Ajax.Updater('assessment_' + a, url, { method: 'get', parameters: pars, evalScripts: true }); 
}

function deleteQuestion(a, q, o)
{
	var answer = confirm ('Are you sure you want to delete question ' + o + '?');
	
	if(answer)
	{
		var url = '/wp-content/plugins/ssassessments/services/updatequestions.php';
		var pars = 'a=' + a + '&delete=' + q + '&ts=' + getTimestamp();
		
		var myAjax = new Ajax.Updater('questions_container', url, { method: 'get', parameters: pars, evalScripts: true }); 
	}	
}

function toggleQuestionEdit(q)
{
	if($('question_'+q).style.display == 'none')
	{	//edit form is shown
		$('question_edit_'+q).hide();
		$('question_'+q).show();
	}
	else //table is shown
	{	
		$('question_'+q).hide();
		$('question_edit_'+q).show();
	}
}

function updateQuestion(a,q)
{	
	if(q)
	{
		if(!$('editquestion_question_'+q).value)
			alert('Please enter a question.');
		else if(!$('editquestion_weight_'+q).value)
			alert('Please enter a question weight.');		
		else
		{
			var url = '/wp-content/plugins/ssassessments/services/updatequestions.php';
			var pars = 'a=' + a + '&q=' + q + '&qorder=' + $('editquestion_order_'+q).value + '&qquestion=' + urlencode($('editquestion_question_'+q).value) + '&qexplanation=' + urlencode($('editquestion_explanation_'+q).value) + '&qweight=' + $('editquestion_weight_'+q).value + '&ts=' + getTimestamp();
			
			var myAjax = new Ajax.Updater('questions_container', url, { method: 'get', parameters: pars, evalScripts: true }); 
		}
	}
	else
	{
		if(!$('newquestion_question').value)
			alert('Please enter a question.');
		else if(!$('newquestion_weight').value)
			alert('Please enter a question weight.');
		else
		{
				var url = '/wp-content/plugins/ssassessments/services/updatequestions.php';
				var pars = 'a=' + a + '&qorder=' + $('newquestion_order').value + '&qquestion=' + urlencode($('newquestion_question').value) + '&qexplanation=' + urlencode($('newquestion_explanation').value) + '&qweight=' + $('newquestion_weight').value + '&ts=' + getTimestamp();
				
				var myAjax = new Ajax.Updater('questions_container', url, { method: 'get', parameters: pars, evalScripts: true }); 
		}
	}
}

function showQuestions(a)
{
	var url = '/wp-content/plugins/ssassessments/services/updatequestions.php';
	var pars = 'a=' + a + '&ts=' + getTimestamp();	
	var myAjax = new Ajax.Updater('questions_container', url, { method: 'get', parameters: pars, evalScripts: true }); 
}
