/******************************************************************************
 *
 * Purpose: Authenticate (base) plugin
 * Author:  Thomas Raffin, SIRAP
 *
 ******************************************************************************
 *
 * Copyright (c) 2008 SIRAP
 *
 * This is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version. See the COPYING file.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with p.mapper; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 ******************************************************************************/

var authAllowSubmit = false; // allow browser to save luser ogin and password

var authDoSubmit = false;

/**
 * OnKeyPress event
 * 
 * Avoid default ENTER key behaviour:
 * - if ENTER is press, then apply the attribut value (= call "Apply").
 * - if an other key is press, the onkeyup will call "Change".
 */
function authUserNameKeyPress(e) {
    var key;
    // IE :
    if (window.event) {
        key = window.event.keyCode;
    } else { // Firefox
        key = e.which;
    }

	// ENTER key :
    if (key == 13) {
        authUserNameApply();
        return false;
    } else {
        return true;
    }
}
function authUserPassKeyPress(e) {
    var key;
    // IE :
    if (window.event) {
        key = window.event.keyCode;
    } else { // Firefox
        key = e.which;
    }

	// ENTER key :
    if (key == 13) {
		authUserPassApply();
        return false;
    } else {
        return true;
    }
}

/**
 * OnKypUp event
 *
 * Enable or disable the "OK" button
 */
function authUserNameChange() {
    var attrval = $('#authUserName').val();
    var btnEnable = false;
    if (attrval) {
    	if (attrval.length > 0) {
    		btnEnable = true;
       	}
	}
	btnEnable ? $('#authUserNameAndPassBtn').removeAttr('disabled') : $('#authUserNameAndPassBtn').attr('disabled','disabled') ;
	authClearAfterUserAndPass();
}

/**
 * Inputs apply
 */
function authUserNameApply() {
	authClearAfterUserAndPass();
	$('#authUserPass').focus();
}
function authUserPassApply() {
	authClearAfterUserAndPass();
	if (authAllowSubmit) {
	   authDoSubmit = true;
    }
	login();
	return false;
}
function authSiteApply() {
	$('#authConfigName').html('').val('').parent().parent().hide();
	login();
}
function authConfigApply() {
	login();
}
function authClearAfterUserAndPass() {
	$('#authUserPass').parent().parent().nextAll().find('.authData').val('#').parent().parent().hide();
}

/**
 * Convert password given by user with md5 and random values mix 
 */
function convertPassVal() {
	var passval = $('#authUserPass').val();
	if ($('#useMd5')) {
		if ($('#useMd5').val()) {
			passval = passval.md5();
		}
	}
	var doSecondHash = false;
	if ($('#usePassPrefix')) {
		if ($('#usePassPrefix').val()) {
			passval = $('#usePassPrefix').val() + passval;
			doSecondHash = true;
		}
	}
	if ($('#usePassSuffix')) {
		if ($('#usePassSuffix').val()) {
			passval = passval + $('#usePassSuffix').val();
			doSecondHash = true;
		}
	}
	if (doSecondHash) {
		passval = passval.md5();
	}
	return passval;
}

/**
 * validation and submit
 */
var auth_nbFormBlock = 0;
function login() {
	var url = auth_xloginURL;
	var params = 'authUserName=' + ($('#authUserName').val() ? $('#authUserName').val() : '');
	var passtmp = convertPassVal();
	params += '&authUserPass=' + (passtmp ? passtmp : '');
	params += '&authSiteName=' + ($('#authSiteName').val() && ($('#authSiteName').val() != "#") ? $('#authSiteName').val() : '');
	params += '&authConfigName=' + ($('#authConfigName').val()  && ($('#authConfigName').val() != "#") ? $('#authConfigName').val() : '');
	params += '&' + SID;
	 
	$('#authMsg').html('');
	if (auth_nbFormBlock == 0) {
		$('#authform').block({"message": "<img src=\"images/loading.gif\" style=\"margin: auto;\" />", "css": {"background": "transparent", "border": "none"}});
	}
	auth_nbFormBlock++;
	
	$.ajax({
		url: url,
		data: params,
		dataType: "json",
		type: 'POST',
		success: function(response) {
			var stop = false;
			
			// errors:
			if (!stop) {
				var msg = response.msg;
				if (typeof(msg) != 'undefined') {
					if (msg.length > 0) {
						authDoSubmit = false;
						loginpage_init();
						$('#authMsg').html(msg);
						stop = true;
					}
				}
			} 
			
			// do submit (to allow browser to save user login and password):
			if (!stop && authDoSubmit) {
				authDoSubmit = false;
				$('#authform').submit();
			}

			// no error:
			if (!stop) {
				var selbox = '';
				var restmp = '';
				
				// site name:
				if (!selbox) {
					restmp = response.sites;
					if (typeof(restmp) != 'undefined') {
						selbox = $('#authSiteName');
					}
				}
				// configuration name:
				var configAutoSelect = '';
				if (!selbox) {
					restmp = response.configs;
					if (typeof(restmp) != 'undefined') {
						selbox = $('#authConfigName');
						var searchLoc = location.search;
						var searchResult = searchLoc.match(/config=([a-zA-Z0-9\_\-]+)/);
						if (searchResult) {
							configAutoSelect = searchResult[1];
						}
					}
				}

				// same things for sites or configurations:
				// populate the select object with options
				if (selbox) {
					var options = '';
					var names = restmp.names.split(','); 
					var descriptions = restmp.descriptions.split(','); 
					for (var iName = 0 ; iName < names.length ; ++iName) {
						var desctmp = descriptions[iName] ? descriptions[iName] : names[iName] 
						options += '<option value=\"' + names[iName] + '\" label=\"' + desctmp + '\">' + desctmp + '</option>\n';
					}
					stop = true;

					// if 2 or more elements, add empty option:
					if (names.length > 1) {
						options = '<option value="#" label="">...</option>\n' + options;
					}
					selbox.html(options);

					// if only 1 element:
					if (selbox.children().length == 1) {
						selbox.change();
						if (jQuery.browser.msie && ($.browser.version >= '6.0')) {
							selbox.parent().hide();
						}
					// if 2 or more:
					} else {
						// select empty option:
						if (jQuery.browser.msie && ($.browser.version >= '6.0')) {
							setTimeout('$(\'#' + selbox.attr('id') + '\').val(\'#\').hide().show().focus();', 500);
						} else {
							selbox.val('#');
						}
						// show selectbox
						selbox.parent().parent().show().focus();
						
						if (configAutoSelect) {
							if (selbox.find('option[value=\'' + configAutoSelect + '\']').length == 1) {
								// bug in IE 6 :
								
								if (jQuery.browser.msie && ($.browser.version >= '6.0')) {
									setTimeout('$(\'#' + selbox.attr('id') + '\').val(\'' + configAutoSelect + '\').change();', 500);
								} else {
									selbox.val(configAutoSelect).change();
								}
							}
						}
					}

					// hide folowing elements:
					var nextField = selbox.parent().parent().next('li');
					if (nextField) {
						nextField.hide();
					}
				}
			}
			
			// redirect with specifyed url in response (ok for really login):
			if (!stop) {
				var url = response.url + '&resetsession=groups,GEOEXT,resultlayer,resultlayers,clientDynamicLayers';
				if (typeof(url) != 'undefined') {
					if (url.length > 0) {
						stop = true;
						$.blockUI({"message": '<div id="auth_redirectMsg">' + auth_loadingStr + '</div>'});
						//document.location = url + (SID ? '&' + SID : ''); 
						setTimeout('redirectPage("' + url + '")', 1000);
					}
				}
			}
			// redirect with specifyed url in response (ok for really login):
			if (!stop) {
				$.blockUI({"message": '<div id="auth_redirectMsg">' + auth_loadingStr + '</div>'});
				setTimeout('window.location.reload()', 1000);
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
            if (window.console) console.log(errorThrown);
			window.location.reload();
		},
		complete: function () {
			if (auth_nbFormBlock > 0) {
				auth_nbFormBlock--;
			}
			if (auth_nbFormBlock == 0) {
				$('#authform').unblock();
			}
		}
	});
}

function loginpage_init() {
	authUserNameChange();
	$('#authSiteName').parent().parent().hide();
	$('#authConfigName').parent().parent().hide();
	$('#authUserName').focus();
	if (authDoSubmit && $('#authUserName').val() && $('#authUserPass').val()) {
		authUserPassApply();
	}
}

function authFormSubmit() {
}


