/**
 * Kewego APIs Sandbox
 * Sept. 2008
 * Written by Axel [ webmaster@vidax.net ]
 * Hosted on Vidax.net [ kewego.vidax.net ]
 *
 * This library was exclusively written for this application.
 * Reproducing, changing, copying or using it for a different
 * usage is forbidden.	
 *
 * This library uses opensource libraries such as jQuery (and
 * some jQuery plugins).
 *
 */

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

var timer_start;
var timer_stop;
var timer_fade;
var log_id = 1;
var last_field_focus;
var slow_query_timer;
var timeout_warning = false;

var matching_fields = new Array();
matching_fields['appKey'] = 'appkey_fld';
matching_fields['appToken'] = 'apptoken_fld';

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#


/* When document is ready */
$(document).ready(function() {
	
	if (typeof(menu_highlight) != 'undefined')
	{
		for (var i in menu_highlight)
		{
			for (var j in menu_highlight[i])
			{
				// Select the current section tab
				
				$('#developers_header ul li').each(function()
				{
					// Extract class suffix
					var regexp = new RegExp('([0-9a-zA-Z\-_]+)' + menu_highlight[i][j], 'g');
        			regexp = regexp.exec($(this).attr('class'));
    
					if (!!regexp && typeof(regexp[1]) != 'undefined')
					{
						// Patch "quick" and dirty for IE 6 with the "Developer account" tab
						if (($.browser.msie && $.browser.version < 7) && $(this).attr('class') == 'dh_menu2_key')
						{			
							$(this).css({background: 'none', backgroundImage: 'none', filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src="/img/notext/menu2_on.png")'});
							$(this).addClass('dh_menu2_on_ie6');
						}
						else
						{
							$(this).attr('class', regexp[1] + 'on');
						}					
					}
				});
			
				// Set staticly the section
				document.section = menu_highlight[i][j];
			}
		}
	}

	/* Main AJAX preferences */
	$.ajaxSetup({
		url: "api/index.php",
		dataType: "json",
		type: "POST",
		async: false,
		error: ajax_error
	});

	/* Displaying last update */
	if (typeof(last_app_update) != 'undefined') {
		$('#last_app_update').append(last_app_update+'. ');
		$('#last_app_update').show();
	}

	/* When an AJAX query starts */
	$('#loading').ajaxStart(function(){
		/* Starting timer */
		timer_start = new Date();

		/* Disabling all input fields */
		$('input').attr('disabled', 'disabled');

		/* Showing "Loading" message */
		$(this).fadeIn('slow');

		/* Checking regularely the query execution time */
		//slow_query_timer = window.setInterval('check_timeout()', '500');
	});

	//$('#tooltip').easydrag();
	//$('#tooltip').setHandler('#tooltip_handler');

	/* Whenever the AJAX query stops */
	$('#loading').ajaxStop(function(){
		/* Getting end timestamp */
		timer_stop = new Date();

		/* Calculating the execution time */
		diff = (timer_stop.getTime() - timer_start.getTime());

		/* Enabling all fields again */
		$('input').attr('disabled', '');

		/* Hiding the "Loading message" */
		$(this).fadeOut('slow');

		/* Killing the timer */
		window.clearInterval(slow_query_timer);
		timeout_warning = false;

		/* Unblocking page if applicable */
		//jQuery.unblockUI();

		/* A bit of a log */
		tolog('Last query executed in '+diff+'ms');
	});

	/* Whenever any object gets the focus */
	$('*').focus(function(){
		current_field_focus = $(this);

		/* Checking whether is title is set */
		title = $(current_field_focus).attr('title');

		/* If it does, displaying the title in the log box */
		if (current_field_focus != last_field_focus && title != '') {
			tolog(title, 'help');
		}
		last_field_focus = current_field_focus;
	});


	/* Trigger for saving AppKey into the cookie */
	$('#save_cookie_lnk').click(function(){
		return save_appkey_cookie();
	});

	/* Checks whether the AppKey cookie exists */
	if ($.cookie('APISandboxappKey')) {
		/* If it does, prefilling the AppKey field */
		$('#appkey_fld').val($.cookie('APISandboxappKey'));
		$('#save_cookie_lnk').hide();
		$('#appkey_fld').attr('readonly', 'readonly');
		$('#appkey_fld').after('<span id="saved_message" class="right_comment">&nbsp;(saved in the cookie <a id="kill_cookie_lnk" href="#"><img src="img/cross.png" width="16" height="16" alt="Kill" title="Kill the cookie" /></a>)</span>');

		/* Trigger for the "Kill cookie" link */
		$('#kill_cookie_lnk').click(function(){
			return kill_cookie();
		});
		tolog('Getting AppKey from cookie');
	}

	/* Trigger for the packages select box */
	$('#packages_slt').change(function() {
		package_changed();
	});

	/* Trigger for the methods select box */
	$('#methods_slt').change(function() {
		method_changed();
	});

	/* Trigger for the clipboard copy link */
	$('#copy_clipboard_lnk').click(function() {
		/* Saving into clipboard */
		$.copy($('#apptoken_fld').val());
		tolog('Value copied into the clipboard', 'success');
		return false;
	});

	/* Trigger for the save preferences button */
	$('#prefs_btn').click(function() {
		preferences_go();
	});

	/* Trigger to run the query */
	$('#query_btn').click(function(){
		run_query();
	});

	/* Loading the package at startup */
	get_packages();

	/* Checking whether package/method sent through URL */
	var current_url = '----'+document.location.hash;
	/* Lookin for arguments */

	if (current_url.indexOf('#') > 0) {
		tmp = current_url.split('#');

		/* Package AND method sent */
		if (tmp.indexOf('/')) {
			tmp = tmp[1].split('/');
			/* Changing option in the drop down */
			$('#packages_slt').selectOptions(tmp[0]);
			/* Triggering action for given package */
			package_changed(tmp[1]);
		}
		/* Only package was sent */
		else {
			$('#packages_slt').selectOptions(tmp[1]);
			package_changed();
		}
	}

});

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

var preferences_go = function() {
	/* Hides what needs to be hidden */
	$('#response_div').hide();
	$('#query_div').hide();
	$('.just_added_li').remove();
	var errors = 0;

	/* Package must be selected */
	if ($('#packages_slt').val() == '--') {
		/* Triggering error */
		$('#packages_slt').effect("highlight", {color: '#FFAFB2'}, 1000);
		errors = errors + 1;
	}

	/* Method must be selected */
	if ($('#methods_slt').val() == '--') {
		/* Triggering error */
		$('#methods_slt').effect("highlight", {color: '#FFAFB2'}, 1000);
		errors = errors + 1;
	}

	/* AppKey must be filled */
	if ($('#appkey_fld').val() == '' || $('#appkey_fld').val().length != 32) {
		/* Triggering error */
		$('#appkey_fld').effect("highlight", {color: '#FFAFB2'}, 1000);
		errors = errors + 1;
	}

	/* No error? Moving to next step */
	if (errors == 0) {
		/* Getting an appToken */
		$('#apptoken_fld').val('');
		check_appkey($('#appkey_fld').val());

		/* Getting the required fields */
		get_fields();
	}
	else {
		tolog(errors+' form field(s) not properly filled', 'warning');
	}
};

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

/* Checking query duration */
var check_timeout = function() {
	timer_stop = new Date();
	diff = (timer_stop.getTime() - timer_start.getTime());

	/* Query is slow? */
	if (diff > 1000) {
		/* Action needed */
		slow_query(diff);
	}
};

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

/* Action when query is slow */
var slow_query = function(time) {
	time = (time / 1000);

	/* Displays an additional error message (with timer) */
    if (timeout_warning == false) {
			jQuery.blockUI({
			message: 'The request is quite slow to complete ('+time.toFixed(1)+'s). Please be patient...',
			css: {
			border: 'none',
			fontSize: '20px',
			padding: '15px',
			backgroundColor: '#000',
			'-webkit-border-radius': '10px',
			'-moz-border-radius': '10px',
			opacity: '.8',
			color: '#fff'
			}
		});
	}
	else {
		$('.blockMsg').text('The request is quite slow to complete ('+time.toFixed(1)+'s). Please be patient...');
	}
	timeout_warning = true;
};

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

/* Executes the query */
var run_query = function() {
	var errors = 0;

	/* Looping on the fields */
	$('#query_builder input').each(function() {
		field = $(this);

		/* If field is mandatory, checking whether data was filled in */
		if ($(field).hasClass('mandatory') == true && $(field).val() == '') {
			/* Triggering error */
			$(field).effect("highlight", {color: '#FFAFB2'}, 1000);
			errors = errors + 1;
		}
	});

	/* No error? Sending query */
	if (errors == 0) {
		tolog('Sending query');
		pack = $('#packages_slt').val();
		method = $('#methods_slt').val();
		serialize = $('#query_builder input').serialize();
		$.ajax({
				 data: 'action=run_query&package='+pack+'&method='+method+'&'+serialize,
				 success: function(response) {

					if (response.error) {
						tolog(response.error, 'warning');
						return false;
					}

					/* Displaying the call URL */
					$('#query_pre').text(response['url']+'?'+serialize);

					if (response['response']['@attributes']) {
						tolog('The API returned an error:<br />'+response['response'][0]+' (errno:&nbsp;'+response['response']['@attributes']['errno']+')', 'warning');
						$('#response_pre').text('The API returned an error: '+response['response'][0]+' (errno: '+response['response']['@attributes']['errno']+')');
						$('#response_pre').removeClass('response_ok').addClass('response_error');
					}
					else {
						/* If auth token returned, saving it */
						if (response['token']) {
							token['username'] = $('#username_fld').val();
							token['token'] = response['token'];
						}

						/* Displaying the server response */
						$('#response_pre').html(response['response']);
						tolog('Displaying response received from server');
						$('#response_pre').removeClass('response_error').addClass('response_ok');
					}

					/* Showing and scrolling to block */
					$('#response_div').fadeIn(800, function() {
						$.scrollTo('#response_div', 1000);
					});
				}
		 });
	} else {
		/* Displaying error */
		tolog(errors+' form field(s) not properly filled', 'warning');
	}
	return false;
};

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

/* Gets the mandatory and optional fields */
var get_fields = function() {
	pack = $('#packages_slt').val();
	method = $('#methods_slt').val();
	tolog('Getting fields for this package/method');

	$.ajax({
			 data: 'action=get_fields&package='+pack+'&method='+method,
			 success: function(response) {
				i = 0;

				/* Processing and displaying the mandatory fields */
				for (j in response['mandatory']) {
					i = i + 1;
					$('#runquery_li').before('<li class="just_added_li"><p class="label">'+ucfirst(j)+' *: </p>'+get_field_code(j, response['mandatory'][j], 'mandatory')+'</li>');
				}
				tolog('Processing mandatory fields (total: '+i+')');

				i = 0;

				/* Processing and displaying the optional fields */
				for (j in response['optional']) {
					i = i + 1;
					$('#runquery_li').before('<li class="just_added_li"><p class="label">'+ucfirst(j)+' : </p>'+get_field_code(j, response['optional'][j], 'optional')+'</li>');
				}
				tolog('Processing optional fields (total: '+i+')');
			 }
	 });
};

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

var get_field_code = function(name, type, cclass) {
	var input = '';
	var field_value = '';

	if (matching_fields[name]) {
		tolog('The "'+name+'" field has been automatically populated');
		field_value = $('#'+matching_fields[name]).val();
	}

	if (type == "file") {
		return '<input type="'+type+'" name="'+name+'" class="'+cclass+'" value="'+field_value+'" /> <span class="right_comment"><strong>Attention</strong>: API Sandbox <u>does not</u> support files upload. Selected file <u>will not</u> be posted among the form</span>';
	}
	return '<input type="'+type+'" name="'+name+'" class="'+cclass+'" value="'+field_value+'" />';
};

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

/* Saves AppKey into the cookie */
var save_appkey_cookie = function() {

	/* Checking AppKey length */
	if ($('#appkey_fld').val().length == 32) {
		$.cookie('APISandboxappKey', $('#appkey_fld').val(), { path: '/', expires: 10 });
		$('#save_cookie_lnk').hide();
		$('#appkey_fld').after('<span id="saved_message" class="right_comment">&nbsp;(saved in the cookie <a id="kill_cookie_lnk" href="#"><img src="img/cross.png" width="16" height="16" alt="Kill" title="Kill the cookie /></a>)</span>');
		$('#appkey_fld').attr('readonly', 'readonly');

		/* Trigger for the kill cookie link */
		$('#kill_cookie_lnk').click(function(){
			return kill_cookie();
		});
		tolog('AppKey saved in the cookie', 'success');
	}
	else {
		/* Displaying error */
		$('#appkey_fld').effect("highlight", {color: '#FFAFB2'}, 1000);
		tolog('Invalid Application Key', 'warning');
	}
	return false;
};

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

/* Delete the cookie */
var kill_cookie = function() {
	$.cookie('APISandboxappKey', '', { path: '/', expires: -10 });
	$('#appkey_fld').attr('readonly', '');
	$('#saved_message').remove();
	$('#save_cookie_lnk').show();
	tolog('Cookie destroyed', 'success');
	return false;
};

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

/* Gets the appToken from the AppKey */
var check_appkey = function(appkey) {
	tolog('Checking AppKey');
	$.ajax({
			 data: 'action=check_appkey&appKey='+appkey,
			 success: function(response) {
				if (response.error) {
					tolog(response.error, 'warning');
					return false;
				}
				/* Displaying appToken */
				$('#apptoken_fld').val(response);
				$('#query_div').fadeIn(800, function() {
					$.scrollTo('#query_div', 1000);
				});
				return true;
			 }
	 });
};

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

/* Getting all available packages */
var get_packages = function() {
	tolog('Loading packages');
	$.ajax({
			 data: 'action=get_packages',
			 success: function(response) {
				/* Looping on all package returned by server */
				i = 0;
				for (j in response) {
					i = i + 1;
					/* Adding an option to the drop down list */
					$('#packages_slt').addOption(response[j], response[j]);
				}

				/* Selects the default option (--) */
				$('#packages_slt').selectOptions('--');

				/* A bit of a visual style */
				$('#packages_slt').effect("highlight", {}, 1000);
				tolog('Packages loaded (total: '+i+')', 'success');
			 }
	 });
};

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

/* Getting all available methods */
var package_changed = function(after_query) {
	pack = $('#packages_slt').val();
	tolog('Getting methods for "'+pack+'"');
	$('#packages_slt').removeOption('--');
	$('#methods_slt').removeOption(/[^--]/);

	$.ajax({
			 data: 'action=get_methods&package='+pack,
			 success: function(response) {
				/* Looping on the methods */
				i = 0;
				for (j in response) {
					i = i + 1;
					/* Adding option to the drop down list */
					$('#methods_slt').addOption(response[j], response[j]);
				}

				/* Counting methods */
				if (i > 0) {
					tolog('Methods loaded (total: '+i+')', 'success');
				} else {
					tolog('No method available for this package', 'info');
				}

				/* Selecting default method (--) */
				$('#methods_slt').selectOptions('--');

				/* Visual enhancement */
				$('#methods_slt').effect("highlight", {}, 1000);

				/* If method set in the URL, selecting it */
				if (typeof(after_query) != 'undefined' && after_query != '') {
					$('#methods_slt').selectOptions(after_query);
					/* If application key filled in */
					if ($('#appkey_fld').val()) {
						/* Submitting form */
						preferences_go();
					}
				}
				else {
					document.location.hash = pack;
				}
			 }
	 });
};

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

/* Whenever the method drop down is changed */
var method_changed = function() {
	pack = $('#packages_slt').val();
	method = $('#methods_slt').val();

	document.location.hash = pack+'/'+method;
};

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

/* Displaying message in the log box */
var tolog = function(message, type) {

	/* Different types of logs => different icons */
	if (type == 'undefined' || type == 'info') {
		img = 'img/information.png';
	}
	else if (type == 'warning') {
		img = 'img/exclamation.png';
	}
	else if (type == 'success') {
		img = 'img/accept.png';
	}
	else if (type == 'help') {
		img = 'img/comment.png';
	}
	else {
		img = 'img/information.png';
	}

	window.clearTimeout(timer_fade);
	now = new Date();

	if (type == 'warning') {
		jQuery.blockUI({
		message: '<p class="warning_close"><img src="img/widget_close.png" width="28" height="28" alt="Close" /></p><p class="warning_img"><img src="img/important.png" width="64" height="64" /></p><p class="warning_message">'+message+'</p>',
			css: {
			border: 'none',
			fontSize: '20px',
			padding: '15px',
			backgroundColor: '#000',
			'-webkit-border-radius': '10px',
			'-moz-border-radius': '10px',
			opacity: '.8',
			color: '#fff'
			}
		});
		$('.warning_close').click(function() {$.unblockUI()});
	}
	/* Adds a new line, with date, icon and message */
	$('#tooltip ol').append('<li><img src="'+img+'" width="16" height="16" />&nbsp;'+now.getHours()+':'+now.getMinutes()+':'+now.getSeconds()+': '+message+'</li>');

	/* Visual highlight */
	$('#tooltip ol li:last').effect("highlight", {}, 500);

	/* Moving the scrollbar down (last line always visible) */
	$('#tooltip ol').scrollTo($('#tooltip ol li:last'), 500);

	/* Counting logs */
	log_id = log_id + 1;

};

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

/* Hides the "Log" box */
var hide_tooltip = function() {
	$('#tooltip').fadeOut('slow');
};

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

/* Changes any word's first character in uppercase mode */
var ucfirst = function(str) {
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1, str.length-1);
};

//_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#

/* Whenever an AJAX query returns an error */
var ajax_error = function() {
	tolog('An AJAX error occurred. Query could not be completed', 'warning');
	return false;
};
