//this function is used to display INFORMATIONAL message to user in a message box
//replace the not friendly alert() function
function popAlert(title,message){
	var myDialog = $('<div title="'+title+'" id="pop_alert">'+message+'</div>');
	myDialog.dialog({close:function(){$(this).dialog('destroy');$(this).remove()},modal:true,buttons:{'Ok':function(){$(this).dialog('close')}}});
}

function popConfirmation(title,message,callback){
	var myDialog = $('<div title="'+title+'" id="pop_alert">'+message+'</div>');
	myDialog.dialog({close:function(){$(this).dialog('destroy');$(this).remove()},modal:true,buttons:{'YES':function(){$(this).dialog('close');eval(callback)},'NO':function(){$(this).dialog('close')}}});
}

//attach suggestion to a field
var indexNavigation = -1;
var myRequest = null;
function attachSuggestion(idField,model,field,showAll){
	//onclick show all possibilities like a combobox
	var myField = $(document.getElementById(idField));
	if(showAll){
		myField.click(function(){
			if($(this).val()=='')findSuggestion(12,this,model,field,true);
		});
	}
	///hide suggestion box on blur
	myField.blur(function(){
		indexNavigation = -1;
		window.setTimeout("$('#suggestions_box').hide();",100);
	});  
	//onkeydown search for all suggestions possible from what is in textbox
	myField.unbind('keydown');
	myField.keydown(function(event){
		keyCode = event.keyCode;
		sender = this;
		fieldRef = field;
		modelRef = model;
		if(keyCode == 27){
			$('#suggestions_box').hide();
		}else{
			//must navigate throught suggestion item(div)
			//if($('#suggestions_box').css('display')=='block'){
			if(keyCode == '38' || keyCode == '40'){
				direction = 39 - keyCode;
				indexNavigation -= direction;
				if(indexNavigation==-1)indexNavigation = $('#suggestions_box').children().length-1;
				if(indexNavigation>$('#suggestions_box').children().length-1)indexNavigation = 0;
				$('.suggestion').css('background-color','#fff');
				$('.suggestion').eq(indexNavigation).css('background-color','#FFCE5A');
				$(sender).val($('.suggestion').eq(indexNavigation).text());
			}else{
				indexNavigation = -1;
				//we cancel request if another key was pressed
				if(myRequest != null)window.clearTimeout(myRequest);
				//got a buffer to wait a little bit before making request to server
				myRequest = window.setTimeout("findSuggestion(keyCode,sender,modelRef,fieldRef);",100);
			}
			//}
		}
	});
}
//
//get suggestion for textboxes by params passed
function findSuggestion(key,sender,model,field,all){
	//if suggestion box is not created we create it
	if(document.getElementById('suggestions_box')== null){
		$('body').append('<div id="suggestions_box" style="background-color:#fff;overflow:auto;max-height:300px;border:1px #000 solid;display:block;position:absolute;z-index:9999;margin-top:-1px"></div>');
	}
	var searchString = "";
	var suggestionsBox = $('#suggestions_box');
	
	//must know if model is inside of a plugins
	if(model.indexOf('.',0) != -1){
		arr = model.split('.');
		plugin = arr[0];
		model = arr[1];
	}else{
		plugin = model;
	}
	if(all){
		searchString = '*';
	}else{
		searchString = $(sender).val();
	}
	if(key !=13){
		if(searchString =='')searchString = '*';
		$.ajax( {
			type : "POST",
			url : "/contents/get_suggestions/"+plugin,
			data:"model="+model+"&string="+searchString+"&field="+field,
			success : function(html) {
				if(html !=''){
					suggestionsBox.width($(sender).width()+1);
//					suggestionsBox.css('width','auto');
					suggestionsBox.css('top',$(sender).offset().top+20 + 'px');
					suggestionsBox.css('left',$(sender).offset().left + 'px');
					suggestionsBox.html(html);
					$('.suggestion').click(function(){$(sender).val($(this).text());suggestionsBox.hide();$(sender).focus()});
					$('.suggestion').css('font-size',$(sender).css('font-size'));
					$('.suggestion').hover(function(){$(this).css('background-color','#FFCE5A');var s = $(this).parent().children();indexNavigation = s.index(this)},function(){$(this).css('background-color','#fff');$(this).css('color','#000');});
					suggestionsBox.show();
				}else{
					suggestionsBox.hide();
				}
			}
		});
	}else{
		suggestionsBox.hide();
	}
}
//
//general function to post any form by ajax to any controller
function submitMyForm(idForm,controller,idMessageContainer){
	var data = $('#'+idForm).serialize();
	var container = $('#'+idMessageContainer);
	$.ajax({
		type : "POST",
		url : controller,
		async : false,
		data:'data='+data,
		success : function(html) {
			//status[0]: to know if action is ok[success,fail]
			//status[1]: message to show
			status = html.split(';');
			container.html(status[1]).attr('class',status[0]);
			refContainer = container;
			if(status[0]=='success'){
				window.setTimeout('refContainer.parent().dialog("close");refContainer.html("").removeClass(status[0])',700);
			}
		}
	});
}
//
//general functions to call a view by ajax
function getViewByAjax(url,idContainer){
	var container = $('#'+idContainer);
	$.ajax({
		async : false,
		type : "POST",
		url : url,
		success : function(html) {
			container.html(html);
		}
	});
}
function getViewByAjaxInDialog(url,title){
	var container = $('<div title="'+title+'"></div>');
	$.ajax({
		async : false,
		type : "POST",
		url : url,
		success : function(html) {
			container.html(html);
			container.dialog({close:function(){$(this).dialog('destroy');$(this).remove()},modal:true,buttons:{'Ok':function(){$(this).dialog('close')}}});
		}
	});
}

//general function to reset value in a form
function clearForm(form) {
// iterate over all of the inputs for the form
  // element that was passed in
	$(':input', form).each(function() {
		var type = this.type;
		var tag = this.tagName.toLowerCase(); // normalize case
		 // it's ok to reset the value attr of text inputs,
		 // password inputs, and textareas
		if (type == 'text' || type == 'password' || tag == 'textarea')
			this.value = "";
			 // checkboxes and radios need to have their checked state cleared
			 // but should *not* have their 'value' changed
		else if (type == 'checkbox' || type == 'radio')
			this.checked = false;
		 // select elements need to have their 'selectedIndex' property set to -1
		 // (this works for both single and multiple select elements)
		else if (tag == 'select')
			this.selectedIndex = -1;
	});
}
