// send email
$('#MessageAddForm').submit(function() {
	$.post("/messages/ajax_add", $(this).serializeArray(), afterValidate, "json");
	return false;
});
function afterValidate(data, status) {
	if (data.errors)
		onError(data.errors);
	else if (data.dberror)
		onDberror(data.dberror);
	else if (data.success)
		onSuccess(data.success);
}
function onSuccess(data) {
	$.modal.close();
	dialogInfo(data);
	clearFields('contact-content');
	$('.error-message').remove();
	reloadCaptcha();
};
function onDberror(data) {
	dialogError(data);
	$('.error-message').remove();
	reloadCaptcha();
}
function onError(data) {
	$('.error-message').remove();
	$.each(data, function(model, errors) {
		for (fieldName in this) {
			var element = $("#" + camelize(model + '_' + fieldName));
			var _insert = $(document.createElement('div')).insertAfter(element);
			_insert.addClass('error-message').text(this[fieldName])
		}
	});
	reloadCaptcha();
	$('#MessageCaptchaCode').val('');
};
function reloadCaptcha() {
	if($('#captcha').size() > 0)
		$('#captcha').attr('src', '/messages/securimage/' + Math.random());
}

// dialog
function dialogMake() {
	$("#dialog").modal({minHeight:35, closeHTML:'', zIndex:100});
}
function dialogInfo(msg) {
	$("#dialog-content").html('<div class="icon32 info"></div><p class="texticon32">'+msg+'</p>');
	dialogMake();
}

function dialogError(msg) {
	$("#dialog-content").html('<div class="icon32 error"></div><p class="texticon32">'+msg+'</p>');
	dialogMake();
}


/**
 * length of an associative array
 */
function associativeArrayLength(array) {
	var length = 0;
	for (var key in array) {
		length++;
	}
	return length;
}


/**
 * clear input fields & textareas in a div
 */
function clearFields(divId) {
	$('#'+divId+' input:not(:hidden), #'+divId+' textarea').val('');
	$('#'+divId+' select').val(0);
}

/**
 * sets text for input fields & select boxes, which ids & content is in the passed in assoc. array
 */
function setValues(array) {
	for(var i in array) {
		try {
			$("#"+i).val(array[i]);
		} catch(err) {}
	}
}

/**
 * make a table zebra
 */
function makeZebraTable(selector) {
	$(selector).each(function() {
		$(this).find('tr').each(function(i) {
			if(i%2==0)
				$(this).addClass('odd');
			$(this).children().each(function(i) {
				if(i==0)
					$(this).addClass('first');
			});
		});
	});
}
makeZebraTable('.zebra');

/**
 * MakesCamelStrings
 */
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 sameHeight(e1, e2) {
	var h1 = $(e1).height(),
		h2 = $(e2).height();
	if( h1>=h2 ) $(e2).height(h1);
	else $(e1).height(h2);
}

/**
 * app specific
 */
function getNextId() {
	if( $('.regbox').size() > 0 ) {
		var max_id=0;
		$('.regbox').each(function(i){
			var cId = $(this).attr('id');
			var tempId = parseInt(cId.split('-')[1])
			
			if( tempId > max_id ){
				max_id = tempId;
			}															
		});
		nr = max_id + 1;
	} else {
		nr = 0;
	}
	return nr;
}

function clearForm() {
	if(document.getElementById('registration_part'))
		clearFields(registration_part + "-form");
	else
		clearFields(edition_part + "-form");
		
	if(document.getElementById('desc') && typeof tinyMCE != 'undefined')
		tinyMCE.get('desc').setContent('');	
	
	if(document.getElementById('tradefair') && typeof tinyMCE != 'undefined')
		tinyMCE.get('tradefair').setContent('');	
	
	if(document.getElementById('participation') && typeof tinyMCE != 'undefined')
		tinyMCE.get('participation').setContent('');	

	$(".edit-foto").hide();
	$('.show-on-edit').hide();
	currentId = '';
	insertedId = '';
}

/**
*	shows info box for a focused input field
*/
$(".aform input").bind('focus', function(){
	
	var current_id = $(this).attr("id");			// id of the current input field
	
	if(current_id) {								// if id exists
		var info_id = "#" + current_id + "_info";	// temp array for splited string
		prev_message = $('#info').text();
		var tmp_text = $(info_id).text()
		$('#info').text(tmp_text);		// apply y position to the info box
		$(info_id).show();							// show info box
	}
});
// hides info box on blur
$(".aform input").bind('blur', function(){
	var current_id = $(this).attr("id");
	if(current_id) {
		var info_id = "#" + current_id + "_info";
		$('#info').text(prev_message);
		$(info_id).hide();
	}
});


function numbersonly(e, decimal) {
	var key, keychar;

	if (window.event) {
	   key = window.event.keyCode;
	}
	else if (e) {
	   key = e.which;
	}
	else {
	   return true;
	}
	keychar = String.fromCharCode(key);
	
	if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27) || (key==44) || (key==46) ) {
	   return true;
	}
	else if ((("0123456789").indexOf(keychar) > -1)) {
	   return true;
	}
	else if (decimal && (keychar == ".")) { 
	  return true;
	}
	else
	   return false;
}

var iIntv;
function showInfo(message) {
	$('#icont-text').text(message);
	var wnd = $(window), doc = $(document),
		pTop = doc.scrollTop(), pLeft = doc.scrollLeft(),
		icont = $('#icont');
	pLeft += (wnd.width() - icont.outerWidth()) / 2;
	pTop += (wnd.height() - icont.outerHeight()) / 2;
	icont.css({top: pTop, left: pLeft}).fadeIn(200);
	iIntv = setTimeout('hideInfo();',5000);
}
function hideInfo() {
	$('#icont').fadeOut(200);
}


var loaderOn = false;
function ShowLoader() {
	loaderOn = true;
	$(document.body).append($('<div id="loader" />').html('<img src="/img/loaderbig.gif" class="loader_img" alt="" /><p>Ładowanie...</p>'));
}
function HideLoader() {
	loaderOn = false;
	$('#loader').remove();
}

/* Ajax overall initialization */
jQuery.ajaxSetup({
	beforeSend: function() {
		if(!loaderOn) ShowLoader();
	},
	complete: function(xhr, status) {
		HideLoader();
	},
    delay: {
        callback: function() {
            alert('Limit czasu przeznaczonego na nawiązanie połączenia z serwerem został przekroczony!');
        },
        time: 10
    },
    timeout: 100000,
    error: function(xhr, status) {
        //alert('Wystąpił nieoczekiwany błąd komunikacji z serwerem!');
    }
});
