afterLoginFunction = function(){};
afterLoginParameters = new Array(0);

function showLoginPopup() {
    AjaxRequest.get({
	'url': 'popups/loginPopup.php',
	'parameters': {	},
	'onSuccess':function(req) {
	    loadIntoElement("popUpDiv", req.responseText);
	    popup('popUpDiv');
	    if (!detectMobileDevice()) document.getElementById("loginFormUsername").focus();
	}
    });
}

function showRegisterPopup() {
    AjaxRequest.get({
	'url': 'popups/registerPopup.php',
	'parameters': {	},
	'onSuccess':function(req) {
	    loadIntoElement("popUpDiv", req.responseText);
	    popup('popUpDiv');
	    if (!detectMobileDevice()) document.getElementById("registerFormUsername").focus();
	}
    });
}

function changeToRegisterPopup() {
    closePopup();
    showRegisterPopup();
}

function switchBackToLoginPopup() {
    closePopup();
    showLoginPopup();
}

function changeToTosPopup() {
    tosPopup = window.open(
	'tosPopup.php',
	'Terms of Service',
	'width=800,height=900,status=no,scrollbars=yes,resizable=yes,location=no'
    );
}

function closePopup() {
    popup('popUpDiv');
}

function submitLogin() {
    AjaxRequest.get(
    {
	'url': 'ajax/login.php',
	'parameters': {
	    'username': document.getElementById("loginFormUsername").value,
	    'password': document.getElementById("loginFormPassword").value,
	    'remember': document.getElementById("loginFormRemember").checked
	},
	'onSuccess':function(req) {
	    if (req.responseText == "") {
		popup('popUpDiv');
		currentUserIsRegistered = 2; //einfach grösser als 1 (= Anonymous)
		if (pageTracker) pageTracker._trackEvent('User', 'Login');
		refreshUserStatus();
		afterLogin();
	    } else {
		loadIntoElement("loginErrorMessage", req.responseText);
	    }
	}
    }
    );
}

function submitRegister() {
    username = document.getElementById("registerFormUsername").value;
    password = document.getElementById("registerFormPassword").value;
    passwordConfirm = document.getElementById("registerFormPasswordConfirm").value;
    email = document.getElementById("registerFormEmail").value;
    url = document.getElementById("registerFormUrl").value;
    terms = document.getElementById("registerFormTerms").checked;
    //invite = document.getElementById("registerFormInvite").value;
    
    if (username == "") loadIntoElement("registerErrorMessage", "Please choose your username.");
    else if (password == "") loadIntoElement("registerErrorMessage", "Please enter a password.");
    else if (password != passwordConfirm) loadIntoElement("registerErrorMessage", "Password confirmation does not match.");
    else if (email == "") loadIntoElement("registerErrorMessage", "Please enter a valid email address.");
    //else if (invite == "") loadIntoElement("registerErrorMessage", "Please enter a valid invitation code.");
    else if (url != "") location.href = "index.php";
    else if (terms == false) loadIntoElement("registerErrorMessage", "Please read and accept our terms of service.");
    else
    {
	AjaxRequest.get(
	{
	    'url': 'ajax/register_request.php',
	    'parameters': {
		'username': username,
		'password': password,
		'passwordConfirm': passwordConfirm,
		'email': email,
		'terms': terms
		//,'invite': invite
	    },
	    'onSuccess':function(req) {
		if (req.responseText == "") {
		    popup('popUpDiv');
		    currentUserIsRegistered = 2; //einfach grösser als 1...
		    if (pageTracker) pageTracker._trackEvent('User', 'Register', username);
		    refreshUserStatus();
		    afterLogin();
		} else {
		    loadIntoElement("registerErrorMessage", req.responseText);
		}
	    }
	}
	);
    }
}

function afterLogin() {
    afterLoginFunction.apply(this, afterLoginParameters);
    afterLoginFunction = function(){};
    afterLoginParameters = new Array(0);
}

function logout() 
{
    AjaxRequest.get(
    {
	'url': 'ajax/logout.php',
	'onSuccess':function(req) {
	    if (req.responseText == "") {
		if (pageTracker) pageTracker._trackEvent('User', 'Logout');
		location.reload();
	    } else {
		loadIntoElement("logoutFeedback", req.responseText);
	    }
	}
    }
    );
}

//TODO: rename to addtagfromirgendwas?
function addUserTags(entity, id) 
{
    if (entity == "ingredient") {
	tagsField = document.getElementById("popup-newTags");
	targetDiv = "popup-existing-user-tags";
    } else if (entity == "composition") {
	tagsField = document.getElementById("newTags");
	targetDiv = "existing-user-tags";
    }
    addUserTag(entity, id, tagsField.value, targetDiv);
    tagsField.value = "";
}

function addUserTag(entity, entityId, tagNames, targetDiv) {
    if (entity != "" && tagNames != "" && entityId > 0) {
	if (userIsRegistered()) {			
	    parameters = new Array(0);
	    parameters['entity'] = entity;
	    parameters['id'] = entityId;
	    parameters['tags'] = tagNames;
			
	    AjaxRequest.get({
		'url': 'ajax/addUserTags.php',
		'parameters': parameters,
		'onSuccess':function(req) {
		    if (pageTracker) pageTracker._trackEvent(entity, 'Add Tag', 'Add tag to ' + entity + ' with ID: ' + entityId + ', Tags: ' + tagNames);
		    loadIntoElement(targetDiv, req.responseText);
		    tagsField.value = "";
		}
	    });
	} else {
	    afterLoginFunction = addUserTag;
	    afterLoginParameters = new Array(4);
	    afterLoginParameters[0] = entity;
	    afterLoginParameters[1] = entityId;
	    afterLoginParameters[2] = tagNames;
	    afterLoginParameters[3] = targetDiv;
	    showLoginPopup();
	}
    }
}

function deleteUserTag(entity, id) 
{
    if (entity == "ingredient") {
	targetDiv = "popup-existing-user-tags";
    } else if (entity == "composition") {
	targetDiv = "existing-user-tags";
    }
	
    parameters = new Array(0);
    parameters['entity'] = entity;
    parameters['id'] = id;
	
    AjaxRequest.get(
    {
	'url': 'ajax/deleteUserTags.php',
	'parameters': parameters,
	'onSuccess':function(req) {
	    if (pageTracker) pageTracker._trackEvent(entity, 'Remove Tag', 'Remove Tag with ID: ' + id);
	    loadIntoElement(targetDiv, req.responseText);
	}
    }
    );
}

function loadIntoElement(elementId, newHtml)
{
    try {
	document.getElementById(elementId).innerHTML = newHtml;
    } catch (e) {
	alert(e + "\nElementId: " + elementId);
    }
}

function userIsRegistered()
{
    if (currentUserIsRegistered > 1) {
	return true;
    }
    return false;
}

function refreshUserStatus ()
{
    AjaxRequest.get({
	'url': 'ajax/getUserStatus.php',
	'onSuccess':function(req) {
	    loadIntoElement("userStatus", req.responseText);
	}
    });
	
    if (document.getElementById("viewComposition")) {
	/*
	 * If we are on combine.php viewing a composition we have to refresh the composition view because some buttons
	 * and labels could change ("I like", "Save", "you").
	 */
	reloadViewableComposition();
    }
}

function showHowToPopup() {
    AjaxRequest.get(
    {
	'url': 'popups/howToPopup.php',
	'parameters': {	},
	'onSuccess':function(req) {
	    loadIntoElement("popUpDiv", req.responseText);
	    popup('popUpDiv');
	}
    });
}

function newCompositionWithIngredientIds(ingredientId) {
    AjaxRequest.get({
	'url': 'ajax/newCompositionWithIngredientIds.php',
	'parameters': {
	    'ingredientId': ingredientId
	},
	'onSuccess':function(req) {
	    if (isNaN(req.responseText)) {
		//TODO: error message
	    } else {
		location.href = 'combine.php?composition_id=' + req.responseText;
	    }
	}
    });
}

function detectMobileDevice() {
    var userAgent = navigator.userAgent;
    var mobileMatch = userAgent.search("iPhone|iPad|BlackBerry|Android|HTC|Nokia|Symbian|SonyEricsson");
    if (mobileMatch > -1) {
	return true;
    }
    return false;
}