var messages  = new Array();
messages['fullname'] = 'The name field is blank';
messages['comments'] = 'The comments field is blank';
messages['company'] = 'The company field is blank';
messages['phone'] = 'The phone field is blank';
messages['country'] = 'The country field is blank';
messages['captcha'] = 'The captcha field is blank';
messages['email'] = 'The email field is blank';
messages['password'] = 'The password field is blank';
messages['passwordn'] = 'The password field is blank';
messages['verify'] = 'The verify password field is blank';
messages['type'] = 'The type field is blank';

/**
* Do this on the onload page
*/
$(function() {
	$("#loader").ajaxStart(function(){$(this).show();});
	$("#loader").ajaxStop(function(){$(this).hide();});

	//Prepare sliding for testimonials
	if($('#slide').length){
		$('#slide').cycle({fx:'fade',speed:500,timeout:7000});
	}
	
	if($('#popup').length){
		if (navigator.appVersion.indexOf("MSIE 6.0") == -1) {
			if ($.cookie('popup') == null) {
				if(typeof(seconds_popup) == "undefined" || seconds_popup == 0 ) {
					seconds_popup = 7;
				}
				$("#popup").show();
				setTimeout('$(".popup").slideDown("slow")', seconds_popup * 1000);
			}
		}
	}

	if('undefined' != typeof(form) && form =='login' ) {
		showForm('login');
	}
	
	if('undefined' != typeof(load_data) && '' != load_data ) {
		var action = '';
		switch(load_data) {
			case 'your-questions':
			case 'my-account': {
				action = 'get-profile';
			}
			break;
		}
		if( '' != action ) {
			loadData(load_data,action);
		}
	}

	if($("#link_login").length) {
		$("#link_login").click(function(){
  			return showForm('login');
		});
	}
	if($("#link_register").length) {
		$("#link_register").click(function(){
  			return showForm('register');
		});
	}
});
loadData = function(form,action) {
	var f = $("form[name='" + form + "']");
	$.post(action_link, { "action": action },
	function(data){
		$(":input[type='text']", f).each(function(i,e){
			var n = $(this).attr('name');
			if( 'undefined' != typeof(data[n]) ) {
				$(this).val(data[n]);
			}
		});
		$(":select", f).each(function(i,e){
			var n = $(this).attr('name');
			if( 'undefined' != typeof(data[n]) ) {
				$(this).val(data[n]);
			}
		});
	}, "json");
};
download = function(alias) {
	$.post(action_link, { 'action': 'download', 'alias': alias },
	function(xml){
		var data	= $('data', xml).text();
		var answer	= $('answer', xml).text();
		var error	= $('error', xml).text();
		if('' != error) {
			alert(error);
			return;
		} else {
			if('' != data ) {
				location.href = data;
				//window.open(data,"Applicure","status=0,location=0");
				return;
			}
		}
	}, "xml");

	return false;
};
showForm = function(target) {
	switch(target) {
		case 'login': {
			$("#login").animate({"left": "-=395px"}, "slow");
			$("#registration").css({"visibility": "hidden"});
		}
		break;
		
		case 'register': {
			$("#login").animate({"left": "+=395px"}, "slow");
			$("#registration").css({"visibility": "visible"});
		}
		break;
	}
	return false;
};

/**
* Check if form has empty element which need to be required
*/
isEmpty = function(f,required) {
	
	var cnt = required.length;
	
	var valid = true;
	
	if(cnt == 0) {
		return true;
	}
	$(':input', f).each(function(j,e){
		for(var i=0; i < cnt; i++) {
			if(required[i] == $(e).attr('name') && $(e).val() == '') {
				$(e).after('<p class="error">' + messages[$(e).attr('name')] + '</p>');
				$(e).focus();
				valid = false;
				return false;
			}
		}
	});
	
	return valid;
};
hideError = function() {
	$('.error').remove();
};

/**
* Function for submit forms on login/registration page
*/
Submit = function(f) {
	hideError();

    var valid = false;
	var required = new Array();

	switch ($(f).attr('name')) {
		case 'quote':
		case 'contact': {
			required = ['fullname','email','captcha','comments'];
		}
		break;
		
		case 'your-questions':
		case 'request-quote': {
			required = ['fullname','email','comments'];
		}
		break;

		case 'partner-application': {
			required = ['fullname','email','phone','company','type','country','comments','captcha'];
		}
		break;
		
		case 'register': {
			required = ['email','password','verify','country'];
		}
		break;
		
		case 'password': {
			required = ['email'];
		}
		break;
		
		case 'edit-password': {
			required = ['password','passwordn','verify'];
		}
		break;
		
		case 'my-account': {
			required = ['email','fullname','country'];
		}
		break;
		
		case 'login': {
			required = ['email','password'];
		}
		break;
	}

	valid = isEmpty(f,required);

    if(valid) {
        $.ajax({
            type	: "POST",
            url		: action_link,
            data	: $(f).serialize(),
			dataType: "xml",
            success	: function(xml) {
                var data	= $('data', xml).text();
                var answer	= $('answer', xml).text();
                var error	= $('error', xml).text();
				var page	= '';
                if('' != error) {
                    alert(error);
                    return;
                } else {
					
					switch( answer ) {
						case 'login': {
							page = "/members/downloads";
						}
						break;
						
						case 'license_groups': {
							alert(data);
							page = "/members/my-account";
						}
						break;

						case 'machine_groups': {
							alert(data);
						}
						break;
						
						case 'register':
						case 'edit-password':
						case 'password':
						case 'partner-application': {
							if( '' != data ) {
								$(f).html(data);
							}
						}
						break;

						case 'your-questions':
						case 'request-quote':
						case 'quote':
						case 'contact': {
							if( '' != data ) {
								$(f).html(data);
							}
							appendPixel(answer);
						}
						break;
						
						case 'my-account': {
							if( '' != data ) {
								alert(data);
							}
						}
						break;
					}
					if('' != page) {
						window.location.replace( page );
					}
				}
            }
        });
    }
    return false;
};
closePopup = function(expire){
	var options = {
		expires: expire,
		path: '/',
		domain: '.applicure.com'
	};
	if (navigator.appVersion.indexOf("MSIE 6.0") == -1) {
		$.cookie('popup', 'true', options);
		$(".popup").slideUp("slow", function(){
			$("#popup").hide();
		});
	}
};
addGroup = function() {
	html = '<tr id="group_row' + group_row + '">'; 
    html += '<td><input type="text" name="hosting_groups[' + group_row + '][name]" value="" /></td>';
	html += '<td><select name="hosting_groups[' + group_row + '][license_type_id]">';
	html += '<option value=""></option>';
	$.each(license_types,function(id,name) {
		html += '<option value="' + id + '">' + name + '</option>';
	});
    html += '</select></td>';
    html += '<td><input type="text" class="date" name="hosting_groups[' + group_row + '][date_expired]" value="" /><input type="hidden" name="hosting_groups[' + group_row + '][hosting_group_id]" value="" /></td>';
	html += '<td><input type="checkbox" name="hosting_groups[' + group_row + '][default]" value="1" /></td>';
	html += '<td></td>';
	html += '<td><button onclick="$(\'#group_row' + group_row + '\').remove();">Remove</button></td>';
	html += '</tr>';
	
	$('#license_groups tbody').append(html);

	group_row ++;
};
appendPixel = function(str) {
	$('body').append('<iframe src="https://www.applicure.com/form-success?_form=' + str + '" width="0" height="0" frameborder="0"></iframe>');
};