/**
 * Croogo
 *
 * available throughout the app
 */
var Croogo = {
    params: {},
    locale: {},
    basePath: '/'
};



$(function($){
	var _loadingDiv = $("#loadingDiv");
	
	$('#registrationCompleteForm').submit(function(){
	    _loadingDiv.show();
	    $.ajax({
		  url: '/messages/send_communication.json',
		  data: $(this).serializeArray(),
		  context: this,
		  type: 'post',
		  dataType: 'json',
		  success: afterValidate
		});
	    return false;
	});
	
	if($('#registrationCompleteForm_training')) {
		var _loadingDiv_training = $("#loadingDiv_training");

		$('#registrationCompleteForm_training').submit(function(){
			_loadingDiv_training.show();
			$.ajax({
			  url: '/messages/send_communication.json',
			  data: $(this).serializeArray(),
			  context: this,
			  type: 'post',
			  dataType: 'json',
			  success: afterValidate
			});
			return false;
		});
	}
	
	setTimeout(initOverLabels, 50);
	
	$(".popup a.moreInfo").hover(
		function() {
			$(this).siblings(".moreInfoPopup").stop(true, true).animate({opacity: "show", bottom: "20"}, "fast");
		},
		function() {
			$(this).siblings(".moreInfoPopup").animate({opacity: "hide", bottom: "30"}, "fast");
		}
	);

});


function afterValidate(data, status)  {
		alert("ARG");
	var elmId = "#" + this.id;
	$(elmId +" .message").remove();
	$(elmId +" .error-message").remove();
	if (data.errors) {
		onError(data.errors, elmId);
	}else if (data.success) {
		onSuccess(data.success, elmId);
	}
}

function onSuccess(data, elmId) {
		alert("ARG success");
	window.setTimeout(function() {
		$("#loadingDiv").hide();
		if($('#loadingDiv_training')) $("#loadingDiv_training").hide();
		if($(elmId +" .successReplace").length > 0){$(elmId +" .successReplace").hide()}
		$(elmId +" .response_success").show();
		window.setTimeout(function() {
			$(elmId +" .response_success").slideUp('slow', function(){
				if($(elmId +" .successReplace").length > 0){$(elmId +" .successReplace").fadeIn('fast')}
			});
		}, 3500);
	}, 500);
};

function onError(data, elmId) {
		alert("ARG error");
    flashMessage(data.message);
    $.each(data.data, function(model, errors) {
        for (fieldName in this) {
			var elementString = "#" + camelize(model + '_' + fieldName);
			if(elmId == '#registrationCompleteForm_training') elementString += '_training';
            var element = $(elementString);
            var _insert = $(document.createElement('div')).insertAfter(element);
            _insert.addClass('error-message').text(this[fieldName]);
            var errorTop = $(_insert).append('<div class="errorTick"></div>');
            _insert.fadeIn('fast');
        }
        $("#loadingDiv").hide();
		if($('#loadingDiv_training')) $("#loadingDiv_training").hide();
    });
};

function flashMessage(message) {
    var _insert = $(document.createElement('div')).css('display', 'none');
    _insert.attr('id', 'flashMessage').addClass('message').text(message);
    _insert.insertBefore($(".posts")).fadeIn();
}

function camelize(string) {
    var a = string.split('_'), i;
    s = [];
    for (i=0; i<a.length; i++){
        s.push(a[i].charAt(0).toUpperCase() + a[i].substring(1));
    }
    s = s.join('');
    return s;
}


function initOverLabels () {
	if (!document.getElementById) return;
	var labels, id, field;
	
	labels = document.getElementsByTagName('label');
	for (var i = 0; i < labels.length; i++) {
	
		if (labels[i].className == 'overlabel') {
		
			// Skip labels that do not have a named association
			// with another field.
			id = labels[i].htmlFor || labels[i].getAttribute('for');
			if (!id || !(field = document.getElementById(id))) {continue;} 
		
			// Change the applied class to hover the label 
			// over the form field.
			labels[i].className = 'overlabel-apply';
			
			// Hide any fields having an initial value.
			if (field.value !== '') {hideLabel(field.getAttribute('id'), true);}
			
			// Set handlers to show and hide labels.
			field.onfocus = function () {hideLabel(this.getAttribute('id'), true);};
			field.onblur = function () {if (this.value === '') {hideLabel(this.getAttribute('id'), false);}};
		
			// Handle clicks to label elements (for Safari).
			labels[i].onclick = function () {
				var id, field;
				id = this.getAttribute('for');
				if (id && (field = document.getElementById(id))) {field.focus();}
			};
	
		}
	}
};

function hideLabel (field_id, hide) {
  var field_for;
  var labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
    field_for = labels[i].htmlFor || labels[i].getAttribute('for');
    if (field_for == field_id) {
      labels[i].style.textIndent = (hide) ? '-3000px' : '0px';
      return true;
    }
  }
}
