function checkAccountType()
{
	var anchor = window.location.search;
	if(userlevel != undefined)
		setSelectedAccount(userlevel);
	else if(anchor != "")
	{
		var pos = anchor.indexOf('&');
		if (pos != -1)
			anchor = anchor.substr(0, pos);
		setSelectedAccount(anchor.substr(1));
	}
	else
		setSelectedAccount('light');
}

function getSelectedProduct()
{
	var a = [10, 20, 30, 40];
	var selected = 0;
	
	for (var i=0; i < 4; i++)
	{
		if ($('#radio-' + a[i] + 'd:checked').length == 1)
		{
			selected = a[i];
			break;
		}
	}
	return selected;
}

function submitProductForm()
{
	var selected = getSelectedProduct();
	
	if (selected == 0)
	{
		o = {'errorDialogTitle': 'Select a product', 'errorDialogText': 'You must select a product before you can continue.'};
		errorDialog.showDialog(o);
		return false;
	}
	
	if (isProductSelectionValid(selected) == false)
		return false;
	
	$("#product-form").submit();
}

function selectAccountType(userlevel, monthly)
{
	var monthOrDayMarker = monthly == true ? 'm' : 'd';
    $("#radio-" + userlevel + monthOrDayMarker).attr("checked", "checked");
	var output = '';
	var price = $("label > input:checked + span.pricetag").html();
	
	switch (userlevel)
	{
		case ACCOUNT_LIGHT:
		    output = 'LIGHT';
		    break;
		case ACCOUNT_BASIC:
		    output = 'BASIC';
		    break;
		case ACCOUNT_PROFESSIONAL:
		    output = 'PROFESSIONAL';
		    break;
		case ACCOUNT_ADVANCED:
		    output = 'ADVANCED';
		    break;
		default:
		    /* Error! */
		    break;
	}
	
	$('#account-type-selected').html(output);
	$('#price-selected').html(price);
	
	return false;
}



function selectSubscriptionType(type, userlevel)
{
    var price = 0;
	var total = 0;
    var description = $('#account-type').html();
    unit_selected = type;
	
	countryVATSelection();
	if (type == 'd')
    {
		description = account_description + ' day pass';
        $('#subscription-length-m').removeAttr('checked');
        $('#subscription-length-w').removeAttr('checked');
        $('#subscription-length-d').attr('checked', 'checked');
    }
	else if (type == 'w')
	{
		description = account_description + ' week pass';
        $('#subscription-length-m').removeAttr('checked');
        $('#subscription-length-w').attr('checked', 'checked');
        $('#subscription-length-d').removeAttr('checked');
	}
    else if (type == 'm')
    {
        description = account_description + ' monthly subscription';
        $('#subscription-length-d').removeAttr('checked');
        $('#subscription-length-w').removeAttr('checked');
        $('#subscription-length-m').attr('checked', 'checked');
    }

	price = '$' + Prices[type]['price'];
	if (includeVAT)
		total = Prices[type]['price'] + Prices[type]['vat'];
	else
		total = Prices[type]['price'];
	$('#total').html('$' + total);

	if (userlevel == 10)
		description = account_description;

    $('#account-type').html(description);
    $('#popup-description').html(description);        
    $('#price').html(price);
    $('#popup-price').html('$' + Prices[type]['first']);
    $('#popup-vat').html('$' + Prices[type]['firstVAT']);
    $('#popup-total').html('$' + (Prices[type]['first'] + Prices[type]['firstVAT']));
    $('#subscription_type').val(type);
    unit_selected = type;
}


function getDiscountPercent(dailyPrice, monthlyPrice, multiple)
{
	var totalDaily = dailyPrice * multiple;
	var discount = 1 - monthlyPrice / totalDaily;
	
	// transform to percent
	discount = Math.round(discount * 100)
	
	return discount;
}


function validateUserForm()
{
	var errors = new Array();
	var fields = new Array();

    fields.push('firstname');
    fields.push('surname');

    // Actual check
	for(var i=0; i<fields.length; i++)
	{
	    if($('#' + fields[i]).val() == '')
	        errors.push(fields[i]);
	}
	
	// password check
	var passwordsMatch = ( $('#new-password').val() == $('#confirm-new-password').val() );

	if(!passwordsMatch || (isNew && $("#new-password").val() == '') )
	{
		if(passwordsMatch)
			drawErrorMessage('new-password', 'Required field');
		else
			drawErrorMessage('new-password', 'Passwords do not match');
			
		errors.push('new-password');
		errors.push('confirm-new-password');
	}
	
	// email check
	if (isNew && $('#email').val() != $('#confirm-email-address').val())
	{
	   drawErrorMessage('email', 'E-mails do not match');
	   //errors.push('email-address')
	}
	else if (!isValidEmail($('#email').val()))
	{
	   drawErrorMessage('email', 'Invalid e-mail')
	   //errors.push('email-address')
	}
	
	var country = $('#country').val();
	if (country == '--' || country == '')
	{
		drawErrorMessage("country", "You must select a country");
		errors.push("country");
	}
	
	if(isNew && $("#user-agreement").attr("checked") !== true)
	{
		drawErrorMessage("user-agreement", "You must accept the user agreement");
		errors.push("user-agreement");
	}

	if(errors.length < 1)
    	return true;

    for(var i=0; i<errors.length; i++)
    {
		if($("#" + errors[i]).attr("type") == "text")
			drawErrorMessage(errors[i], "Required field");
    }

	
    
    return false;
}

function saveUser()
{
	// reset error messages
	$(".field-error-message").remove();

	if(!validateUserForm())
		return false;

	var postData = $("#userform").serialize();

	$.post("/ajax/user.php", postData, saveUserCallback);
	
	return false;
}

function saveUserCallback(response)
{
	//TODO: this function must really be sorted out! go json all the way!!
	var returnVal = false;
	
	var key = '';
	var value = '';
	var mode = 0;
	
	// Modes:
	// 0 - Reading a key
	// 1 - Reading a value

	// parse stuff here
	for(var i=0; i<response.length; i++)
	{
		var character = response.charAt(i);
		
		// end of the line, time to do stuff
		if(character == "\n")
		{
			if(key=='ok')
			{
			    drawSavedMessage('user-page-title', value);
			    returnVal = true;
			}
			else if (key == 'downgraded')
			{
				document.location = document.location;
			}
			else
			{
			    drawErrorMessage(key, value);
			}
			key = '';
			value = '';
			mode = 0;
			continue;
		}
		
		// switch to fill value instead
		if(character == "|")
		{
			mode = 1;
			continue;
		}
		
		if(mode == 0)
		    key += character;
		else
		    value += character;
	}

	if(returnVal)
	{
		if (isEditing)
			$.scrollTo($("a[name=top]"), 200);
		$("#paymentForm").submit();
	}
	
	return returnVal;
}


function drawErrorMessage(field, message)
{
	$("#" + field).after('<div class="field-error-message">' + message + "</div>\n");
}

function drawSavedMessage(elementID, message)
{
	$('div.announcement-box').remove();		
	$("#" + elementID).after('<div class="announcement-box">' + message + "</div>");
	
	// Hide this if we are doing to auriga
	if (message.substr(0, 5) == '<form')
		$('#' + elementID).hide();
}


function showOrderPopup(elementID)
{
	var element = $('#' + elementID);
	if (element.is(':visible'))
		return;
	else
		element.show();
}

function checkSubmitConditions(reg)
{
	if (isOldCustomer && unit_selected == 'm')
	{
		showPaypalDialog();
		return false;
	}
	// reset error messages
    $(".field-error-message").remove();

	if (!validateUserForm())
	    return false;

	if ($('#subscription-length-d').is(':disabled') &&
		$('#subscription-length-w').is(':disabled') &&
		$('#subscription-length-m').is(':disabled'))
	{
		errorDialog.showDialog({
		'errorDialogTitle': 'Invalid choice',
		'errorDialogText' : 'You can not purchase this product. Please select another one.',
		'errorDialogText2' : ''});

		return false;
	}

	var isMonthlyUpgrade = unit_selected == 'm' && account_type > userlevel_monthly ? true : false;

	if ( canDoMonthlyUpgrade && isMonthlyUpgrade && account_type > ACCOUNT_LIGHT && reg != true)
	{
	    confirmDialog.showDialog();
        //$.scrollTo($("a[name=top]"), 200);
	}
	else if (isMonthlyDowngrade)
	{
		if (includeVAT)
			$('#popup-vat-downgrade').html('$' + (Prices['m']['vat']) );
		else
			$('#popup-vat-downgrade').html('$0');
		$('#popup-price-downgrade').html('$' + Prices['m']['price']);
		$('#popup-total-downgrade').html('$' + Prices['m']['total']);
		downgradeDialog.showDialog();
	}
	else
	{
		saveUser();
	}
	
	return false;
}

function checkSubmitConditionsEdit()
{
	// reset error messages
    $(".field-error-message").remove();
	
	if (!validateUserForm())
	    return false;
		
	var postData = $("#userform").serialize();

	$.post("/ajax/myaccount.php", postData, saveUserCallback);
}

function confirmPaymentCallback(dialog, button)
{
    if (button == 'saveButton')
    {
    	$("#confirmPaymentPopup > div").html('Waiting for payment server...');
    	saveUser();
    }
    else if (button == 'cancelButton')
    {
    	dialog.hideDialog();
    }
}

function showPaypalDialog()
{
	errorDialog.showDialog({
		'errorDialogTitle': 'Information',
		'errorDialogText' : 'We have recently switched from PayPal to a new, integrated payment solution.',
		'errorDialogText2' : 'To upgrade or cancel your subscription you need to contact us at <a href="mailto:support@loadimpact.com">support@loadimpact.com</a> so we can transfer your account to the new system.'});
}

function drawColoredProgressBar(id, percentage, height)
{
	percentage = parseInt(percentage);
	
	if (percentage > 100)
		percentage = 100;

	if (height == undefined)
		height = '8';
	
	var html = ''
	+ '<div class="progress-bar" style="height: ' + height + 'px">'
	+ '<div class="progress-bar-bar" style="height: ' + height + 'px; background-color: #'  + getPercentageSeverityColor(percentage) + '; width: ' + percentage + '%;"></div>'
	+ '</div>';
	
	$("#" + id).html(html);
}


function getPercentageSeverityColor(percentage)
{
	percentage = parseInt(percentage);
	
	if (percentage >= 90)
		return 'cc0000';
	if (percentage >= 70)
		return 'ff9900';
	if (percentage >= 45)
		return 'ffff33';
		
	return '669900';
}

function countryVATSelection()
{
	var c = $('#country').val();

	if (c == 'SE')
	{
		includeVAT = true;
		$('#vat').html('$' + Prices[unit_selected]['vat']);
		Prices[unit_selected]['total'] = Prices[unit_selected]['price'] + Prices[unit_selected]['vat'];
	}
	else
	{
		includeVAT = false;
		$('#vat').html('$0');
		Prices[unit_selected]['total'] = Prices[unit_selected]['price'];
	}

	$('#total').html('$' + Prices[unit_selected]['total']);
}


function campaignKeyPress()
{
	var date = new Date();
	campaignKeystroke = date.getTime();
	clearTimeout(campaignTimeoutId);
	campaignTimeoutId = setTimeout('campaignControl();', 600);
}

function campaignControl()
{
	var date = new Date();
	if ((date.getTime() - campaignKeystroke) > 400)
		validateCampaignCode();
}

function validateCampaignCode()
{
	var campaign = $('#campaign').val();
	if (campaign == '')
	{
		$('#campaignLabel > .field-error-message').remove();
		$('#campaignIcon').css('display', 'none');
		return;
	}

	$.ajax({type: 'GET', url: '/ajax/campaign.php', data: 'code=' + campaign, success: function(msg) {
	
		if (msg != 'no')	
		{
			$('#campaignIcon').css('display', 'inline');
			var discount = (parseInt(msg) / 100) * 1;
			$('#campaignLabel > .field-error-message').remove();
		}
		else
		{
			$('#campaignIcon').css('display', 'none');
			$('#campaignLabel > .field-error-message').remove();
			drawErrorMessage("campaign", "Invalid campaign code");
		}
	}});
}

function reactivateCallback(dialog, action)
{
	if (action == "yesButton")
		window.location = '/cancel.php?reactivate&id=' + reactivateId;
	else
		dialog.hideDialog();
}
