/* general functions. backendmaker.com by Enrique Gonzalez Alonso
*/

function initjs() { //common init functions for all templates
  drawForm(); //drawing the edit form
  
  // Interface for list and multilist type of fields
  $(".relation_starter").click(function () {
      var lid=$(this).attr("id");
      lid = lid.substring(0,lid.lastIndexOf('_'));
      $("#"+lid+"_relationcontainer").toggle("slow");
  });
  
  $('.removefromlist').click(function() {
      var lid=$(this).attr("id");
      lid = lid.substring(0,lid.indexOf('_'));
      $('#'+lid+'_dest option:selected').remove();
  });
  
  $('.singletab').click(function(ev) {
      ev.preventDefault();
      $('ul.tabs li').removeClass('current');
      var arrlid = $(this).attr("id").split('_');
      $('dd[id^=ddtabcomp]').hide();
      $('dt[id^=dttabcomp]').hide();
      $('dd[id^=ddtabcomp'+arrlid[1]+']').show();
      $('dt[id^=dttabcomp'+arrlid[1]+']').show();
      $(this).parent().addClass('current');
  });
  
  $('.removefromlistb').click(function() {
      var lid=$(this).attr("id");
      lid = lid.substring(0,lid.indexOf('_'));
      $('#'+lid+'_holder').val('');
      $('#'+lid).val('');
  });
  
  $(".relationcontainer").hide();
  
  //if there are "date" or "datetime" fields, we load the calendar plugin 
  if (table_actual.istherekindof("date") || table_actual.istherekindof("datetime") || table_actual.istherekindof("time")) { 
        loadCss("css/anytime.css");
             var dateString=generalConfig.dateformat.replace("yyyy","%Y");
	         dateString=dateString.replace("mm","%m");
   	         dateString=dateString.replace("dd","%d");
   	         dateString=dateString.replace(/-/gi,"/");
			 $.each(table_actual.fields, function(i, value) {  
				  	 if ((value.kindof=='datetime') || (value.kindof=='date') || (value.kindof=='time')) { 
				  	   if (value.kindof=='time')
   	             			calendarDateString="%H:%i";
   	         		   else if (value.kindof=='datetime')   
   	             			calendarDateString=dateString+" %H:%i";
   	             	   else calendarDateString=dateString;		
				  	   $("#"+i).AnyTime_picker(
      					{ format: calendarDateString,
        				  placement: "popup",
        				  labelHour: lng.hour, 
        				  labelMinute:lng.minute,
        				  labelYear: lng.year, 
        				  labelMonth:lng.month,
        				  labelDayOfMonth:lng.dmonth,
        				  labelTitle:lng.select,
        				  dayAbbreviations:lng.shortdaynamesstartingatsunday,
        				  monthAbbreviations:lng.monthAbbreviations,
        				  monthNames:lng.monthnames, 
        				  firstDOW:1
        				  });
				  	   }
			 });   
			   
  }

 //if there are "file" or "image" fields, we load the ajax file upload plugin
 if (table_actual.istherekindof("file") || table_actual.istherekindof("image"))  
         $.getScript("js/jquery.ajax_upload.0.6.js", function(){
         setTimeout(function(){
 					  $.each(table_actual.fields, function(i, value) {  
 					  	    if ((value.kindof=='image') || (value.kindof=='file')) {
				  	   		  var typeofconfig={ uploaddir:value.uploaddir };
				  	   		  if (value.hasOwnProperty('maxfilesize'))
				  	   		     typeofconfig.maxfilesize=value.maxfilesize; 
				  	   		  if (value.hasOwnProperty('imageresize'))
				  	   		     typeofconfig.imageresize=value.imageresize;
				  	   		  if (value.hasOwnProperty('createthumb'))
				  	   		     typeofconfig.createthumb=value.createthumb; 
				  	   		  if (value.hasOwnProperty('morethumbs'))  
				  	   		     typeofconfig.morethumbs=value.morethumbs;      
    		            filepointers[i]={ submited:false, upload:$.ajax_upload('#'+i+'_','#'+i+'_empty', { action: 'ajax/uploads.php', name: i+"_", data: { config: JSON.stringify(typeofconfig) }, 
                                                                       onSubmit: function(file, extension) { if (value.hasOwnProperty('allowedtypes')) return checkValidExtension(value.allowedtypes, file, extension); },
                                                                       onComplete: function(name, file, response) { continueUploading(name, file, response); }
                                                               })
                    }
	   	            } 
				    }); 	   
			      }, 1000);
         });  

//Starting any TinyMCE text area
  if (table_actual.istherekindof("tinymce")) {
    $.each(table_actual.fields, function(i, value){ 
     if (value.kindof=="tinymce")
          $("#"+i+"_").tinymce();
    });
  }
  
if (table_actual.istherekindof("coords")) {
$.each(table_actual.fields, function(i, value){ 
     if (value.kindof=="coords")
          $('#address-submit-'+i).click(function(ev){
  					   ev.preventDefault();
  					   addressQuery(i);
  		  });
     });
  }  

}  

function initValidator() {
   $("#form").validator({ 
         lang: 'es',
         effect: 'wall', 
         container: '#errors',
         errorInputEvent: null
        }).bind("onBeforeValidate", function(e, els)  {
	fillFieldsBeforeValidation();
		}).submit(function(e) {
  		 if (!e.isDefaultPrevented()) {
  		    $("#errors").hide();
  		    e.preventDefault();
  		    saveFormFiles();
  		 }
        }); 
        $.tools.validator.localize("es", {
        '*'			    : lng.validationwrong,
		':email'  		: lng.validationemail,
		':url'  		: lng.validationurl,
		':number' 		: lng.validationnumber,
		'[max]'	 		: lng.validationbelow+' $1',
  		'[min]'	 		: lng.validationabove+' $1',
		'[required]' 	: lng.validationempty
		});
		$.tools.validator.addEffect("wall", function(errors, event) {
			var wall = $(this.getConf().container).fadeIn();
		    wall.find("p").remove();
		    $.each(errors, function(index, error) {
		     wall.append(
			"<p><strong>" +table_actual.fields[error.input.attr("name")].fieldName+ "</strong>: " +error.messages[0]+ "</p>"
		    );		
	    });
        }, function(inputs)  {
        });
}

//check if a file or image that we are going to upload has the right extension
function checkValidExtension(types, file, extension) {  
 if ($.inArray(extension.toLowerCase(), types) === -1){	
			showStatus(lng.fileextnotallowed+": "+file,5000);
	    loaderMain('none');
	    return false;
 } else return true;
}

//function for uploading the following file on the list, Ajax callback for uploading files function
function continueUploading(name, file, response) {
	if (lng.hasOwnProperty(response)) tex=lng[response]+": "+file;
	else { 
      tex=lng.erroruploaded+" "+file+": "+response;
 	    loaderMain('none');
  }
	showStatus(tex);
	if (response=="successuploaded") { 
		var p=name.substr(0,name.length-1);
		filepointers[p].submited=true;
		saveFormFiles();    
	} else  loaderMain('none');
}

//if there is files or images, here we start to upload them. We use a pointers array to write down the "uploaded" state of each file
function saveFormFiles() {
	var element_count=0;
	 loaderMain('block'); 
	$.each(filepointers, function(k,v){
      if (!v.submited) {
		    if ($('input[name='+k+'_]').val().length > 0) {
          showStatus("<img src='images/ajax-loader.gif' class='absmiddle' alt='loading' />&nbsp;"+lng.uploadingfile+" "+$('input[name='+k+'_]').val());
		      v['upload'].submit();
		      return false;
		    } else v.submited=true;
     	}
     element_count++; 	
  });
  if (element_count==objectSize(filepointers)) { 
  	 $.each(filepointers, function(k,v){
        v.submited=false;
     });
  	saveFormData();
  }
}

function fillFieldsBeforeValidation() {
$.each(table_actual.fields, function(i, value) {
  	switch (value.kindof) {
  		case "tinymce": 
                    var alt_textarea=i+"_";
       			   $('#'+i).val(tinyMCE.get(alt_textarea).getContent()); break;
        case "multilist": var content="";
                        $('#'+i+'_dest option').each(function(i, element){
	 	    		                   content+=$(element).val()+",";
                        }); 
                        $('#'+i).val(content.substr(0,content.length-1));  break;			                
    }
  });	
}
// this function starts when all the files has been uploaded or if there is not files. We save the form data in the database.
function saveFormData() {
  fillFieldsBeforeValidation();
  var formdata=$('#form').serializeArray();
  formdata = $.grep(formdata, function(svalue, si){
    if (editidvalue!=null)
      return ((si == 0) || ((svalue.value!=tempfieldsholder[svalue.name]) && (table_actual.fields.hasOwnProperty(svalue.name))));
    else return ((si == 0) || (table_actual.fields.hasOwnProperty(svalue.name)));  
  });
 if (formdata.length >1) {
	$.ajax({
    url: 'ajax/dbdata_u.php',
    type: 'POST',
    data: formdata, 
    success: function(responseText){
    	var tex;
	    if (lng.hasOwnProperty(responseText)) tex=lng[responseText];
	    else tex=lng.errorinsert+" "+responseText;
	   	showStatus(tex,5000);
	   	refreshtempfieldsholder(formdata);
	    dolist();
	    loaderMain('none');
    }
  });
 } else loaderMain('none'); 
}

//clearing the editing form
function clearForm() {
  $("#errors").hide();
  $.each(table_actual.fields, function(i, value) {
  	formFieldSet(i,value,"");
  });	
}

//switch from paginated list to edit form
function switchForm() { 
	if ($("#editing").size() && $("#list").size()) {
  		$('#editing').toggle(); 
  		$('#list').toggle(); 
		$("#status_edit").html('');   
        $("#status_list").html('');
        $("#errors").hide();
  	}
}

//shows a clean form for inserting new records
function newForm() {
  switchForm();
  tempfieldsholder={};
  fillfields_conf(null);
	clearForm();
	$.each(table_actual.fields, function(i, value) {
  	if (value.hasOwnProperty('initvalue'))
  	  formFieldSet(i,value,value.initvalue);
  });
}

//function for add conditions to filter the list of records of a table
function searchForm(field,relation,value) {
	if(field.length > 0) {
	  if (relation=="like") value="%"+value+"%";
	  filterconditions={ filteras : { field: field, relation: relation, value: value } };
  }
  else filterconditions=null;
  pagina=0;	
  table_actual.bounds.start=0;
	dolist();
}

//pagination lists
function dolist() {
 if ($("#list").size()) {
  var fields=kindofFields();
 	var listconf={ table: table_actual.table, 
                 keyfield: table_actual.keyfield, 
				         order: table_actual.order, 
				         op: 'l',
				         fields:fields,
				         relations: table_actual.relationFields,
				         bounds: table_actual.bounds,
				         listfields:table_actual.listFields, 
				         conditionals:filterconditions          
				          }; 
  loaderMain('block');				          
	$.ajax({
    url: 'ajax/dbdata.php',
    type: 'POST',
    data: { postdata:JSON.stringify(listconf)},
    success: function(msg){
      if ((msg.length>0) && (msg!='false')) {
    	var jsResp=JSON.parse(msg);
    	//we need to know the total of fields of the query, for the pagination
    	var totalconf={ table: table_actual.table, 
                      keyfield: table_actual.keyfield, 
				              op: 'n',
				              conditionals:filterconditions,
                      relations: table_actual.relationFields        
				          }; 
    	$.ajax({
        url: 'ajax/dbdata.php',
        type: 'POST',
        data: { postdata:JSON.stringify(totalconf)}, 
        success: function(total){
   	       var htmlresponse=""; 
	         htmlresponse="<table id=\"listing\" class=\"datatable full companylist\" summary=\"Table list\">"; 
		       if (total==0) 
		       {
			       htmlresponse+="<tr><td>"+lng.norecords+"</td></tr>";
		       }
		       else {
		       htmlresponse+="<thead><tr>";	
		       img_sort= (table_actual.order[1].toLowerCase()=="asc") ? "arrow-up.png": "arrow-down.png"; 
		       $.each(table_actual.listFields, function() {
			 	     htmlresponse+="<th>";
		 	       htmlresponse+="<a href='javascript:doorder(\""+this+"\");'>"+table_actual.fields[this].fieldName+"</a>";
		 	       if (table_actual.order[0]==this) htmlresponse+="&nbsp;<img src='images/"+img_sort+"' alt='' />";
		 	       htmlresponse+="</th>";		 	   
 		       });
		       htmlresponse+="<th></th></tr></thead>";		 
		       htmlresponse+="<tbody>";		
		       $.each(jsResp, function(key,value) {
				 	   htmlresponse+="<tr>";
		 	       $.each(table_actual.listFields, function(k,v) {
		 	          var bvalue=eval("value."+this);
			 	        var njk=(table_actual.fields[v].kindof=="multilist") ? "id='multi_"+key+"'" : "";
			 	        htmlresponse+="<td "+njk+">";
			 	        htmlresponse+="<a href=\"javascript:doedit("+eval("value."+table_actual.keyfield)+");\">";
			 	        switch (table_actual.fields[v].kindof) {
			 	        	case "image": var thumbdir=(table_actual.fields[v].hasOwnProperty("createthumb")) ? "thumbs/" : "";
                                htmlresponse+="<div class='imageloading' id='"+eval("value."+table_actual.keyfield)+"_listimg'></div>";
                                imageresizeonload("#"+eval("value."+table_actual.keyfield)+"_listimg", table_actual.fields[v].uploaddir+'/'+thumbdir+bvalue, 50); break;
                  case "datetime": case "time": case "date": htmlresponse+=formatDates(bvalue,table_actual.fields[v].kindof); break;
                  case "bool": $.each(table_actual.fields[v].values, function (ki,kv) { 
                               if (bvalue==ki) {
                                    htmlresponse+=kv;
                                    return false; 
                                }
                               }); break; 
                   case "multilist": 
                      var searchconf={       
                         value: bvalue,
				         relations:table_actual.relationFields[v]
                       };
                        $.ajax({
                          url: 'ajax/somefieldvalues.php',
                          type: 'POST',
                          data: { postdata:JSON.stringify(searchconf) }, 
                          success: function(msgt){
                            var jjsResp=JSON.parse(msgt);
    	                    htmlresponse2="";
    	                    $.each(jjsResp, function(mkey,mvalue) { 
    	                      htmlresponse2+=mvalue['value']+" "; 
    	                    });
    	                   $("#multi_"+key).html(htmlresponse2);
                          }
                       });
                       
                    
                  break;             
                  default: htmlresponse+=bvalue;
			 	        }
		 	          htmlresponse+="</a>";
		 	          htmlresponse+="</td>";		 	   
		 	       });
		 	       htmlresponse+="<td>";
			       htmlresponse+="<a href=\"javascript:dodelete("+eval("value."+table_actual.keyfield)+");\"><img src='images/bin-metal.png' alt='"+lng.deletecontent+"' /></a></td>";
		 	       htmlresponse+="</tr>";
		       });
		     }
		     htmlresponse+="</tbody></table>";
		     $('#list_table').html(htmlresponse); 
		     if (total > table_actual.bounds.limit){
			      limt=(((pagina*table_actual.bounds.limit)+table_actual.bounds.limit) > total) ? total : ((pagina*table_actual.bounds.limit)+table_actual.bounds.limit);
		        $("#pagresume").html('<h3>'+lng.showing+' '+((pagina*table_actual.bounds.limit)+1)+ ' '+lng.to+' ' + limt +' '+lng.of+' ' +total+' '+lng.records+'</h3>');
		        $("#pagination").pagination(total, { current_page:pagina,items_per_page:table_actual.bounds.limit,callback:dopagination	});
		     } else {
		     	$("#pagresume").html('<h3>&nbsp;</h3>');
		     	$("#pagination").html('');
		    }
        }
     });	
    } else { //the query returned false, no records
  	  $('#list_table').html("<h3>&nbsp;</h3><p>"+lng.norecords+"</p>");
      $("#pagresume").html('<h3>&nbsp;</h3>');
  	  $("#pagination").html('');
   	  }
   
   loaderMain('none');
   } 
  });
 }
}

//function called when we 'change page' in a pagination list
function dopagination(p,q) {
	pagina=p;
	table_actual.bounds.start=p * table_actual.bounds.limit;
	dolist();
}

//function to change the order of a listing to a field
function doorder(c) {
	pagina=0;
	table_actual.bounds.start=0;
	if (c==table_actual.order[0])
	 table_actual.order[1]=(table_actual.order[1].toLowerCase()=="asc") ? "desc": "asc"; 
	table_actual.order[0]=c;
	dolist();
}

//drawing the edition form
function drawForm() {
	var comp="";
	var tabr="";
	var labl;
	var counter=1;
	var tabcounter=0;	
	if (objectSize(table_actual.tabs) > 0) {
	 tabr="<ul class='tabs'>";
	    var fdr=0;
		$.each(table_actual.tabs, function(i, value) {
		    var gbsty=(fdr==0) ? "class='current'": "";
			tabr+="<li "+gbsty+"><a class='singletab' id='tab_"+(fdr++)+"' href=''>"+value+"</a></li>";
		});
	 tabr+="</ul>";
	 $("#tabscontainer").html(tabr);	
	}

	$.each(table_actual.fields, function(i, value) {
	      var tagv="";
	      var thetype="type='text'";
	      var minl="";
	      var maxl="";
	      var patt="";
	     
	    if (value.hasOwnProperty('validation')) {
	      if (value.validation.required==true)
	        tagv="required='required'";
	      
	      if (value.validation.hasOwnProperty('valideas')) {
		  switch (value.validation.valideas) {
			 case 'number': thetype="type='number'"; break;
	     	 case 'email': thetype="type='email'"; break;
	     	 case 'url': thetype="type='url'"; break;	 
	     	 case 'time': thetype="type='time'"; break;	 
	     	 case 'integer': patt="pattern='[0-9]+'"; break;
	     	 case 'letter': patt="pattern='[a-zA-Z]'"; break;
	     }

		 if ((value.validation.hasOwnProperty('min')) || (value.validation.hasOwnProperty('max'))) {
             if (value.validation.hasOwnProperty('min')) {
              minl="min='"+value.validation.min+"'";
             }
			 if (value.validation.hasOwnProperty('max')) {
			 maxl="max='"+value.validation.max+"'";
             }
		 }
		}
	      
	    }
	    
	    if (objectSize(table_actual.tabs) > 0) {
		  $.each(table_actual.tabs, function(ib, valueb) {
			if ((ib==i) && (counter>1)) {
				tabcounter++;
			}
		  });
		}
		
		var rowstyl = (counter%2==0) ? "class='ddeven'" : "";
		var dtid = "dttabcomp"+tabcounter+"_"+counter;
		var ddid = "ddtabcomp"+tabcounter+"_"+counter;
	    var ddestilo=(tabcounter > 0) ? " style='display:none'" : "";
		labl="<dt id='"+dtid+"' "+rowstyl+ddestilo+"><label for = '"+i+"' accesskey = '"+i.substr(0,1)+"'>"+value.fieldName+":</label></dt>";
		switch(value.kindof) {
			case 'hidden': comp="<input type='hidden' id='"+i+"' name='"+i+"' />\n"; break;
			case 'text': var lngth=(value.hasOwnProperty('maxlength')) ? "maxlength='"+value.maxlength+"'" : ""; 
			             var sz=(value.hasOwnProperty('size')) ? "size='"+value.size+"'" : "";
                   comp="<input "+thetype+" id='"+i+"' name='"+i+"' tabindex = '"+counter+"' title = '"+value.fieldName+"' "+lngth+" "+sz+" "+tagv+" "+minl+" "+maxl+" "+patt+" />\n"; break;
			case 'password': var lngth=(value.hasOwnProperty('maxlength')) ? "maxlength='"+value.maxlength+"'" : ""; 
			                 var sz=(value.hasOwnProperty('size')) ? "size='"+value.size+"'" : ""; 
                       comp="<input type='password' id='"+i+"' name='"+i+"' tabindex = '"+counter+"' title = '"+value.fieldName+"' "+lngth+" "+sz+" "+tagv+" "+minl+" "+maxl+" "+patt+" />\n"; break;
			case 'textarea': comp="<textarea id='"+i+"' name='"+i+"' tabindex = '"+counter+"' title = '"+value.fieldName+"' "+tagv+" "+minl+" "+maxl+" style='width:730px; height:150px'></textarea>\n"; break; 
			case 'tinymce':  comp="<textarea class='tinymce' id='"+i+"_' name='"+i+"_' tabindex = '"+counter+"' style='width:740px; height:300px' title = '"+value.fieldName+"' ></textarea>"; 
			                 comp+="\n<input type='hidden' id='"+i+"' name='"+i+"' "+tagv+" "+minl+" "+maxl+"  />\n"; 
			                 comp+="<div class='clear'></div>";
		                   break;
			case 'datetime': case "date": case "time": comp="<input type='text' "+tagv+" id='"+i+"' name='"+i+"' class='halfsize' tabindex = '"+counter+"' title = '"+value.fieldName+"' />\n"; break;
     		 case 'list': var lngth=(value.hasOwnProperty('maxlength')) ? "maxlength='"+value.maxlength+"'" : ""; 
			                  var sz=(value.hasOwnProperty('size')) ? "size='"+value.size+"'" : "";
                              comp="<div class='fl'><input type='text' id='"+i+"_holder' name='"+i+"_holder' tabindex = '"+counter+"' readonly='readonly' title = '"+value.fieldName+"' "+lngth+" "+sz+" />&nbsp;<img src='images/arrow_big.png' class='relation_starter absmiddle' id='"+i+"_relationstarter' alt='' /><br class='clearleft' /><button type='button' id='"+i+"_remove' class='button button-orange removefromlistb' >"+lng.remove+"</button></div>\n"; 
			                  comp+="<div id='"+i+"_relationcontainer' class='fl relationcontainer'><div class='ploader' id='"+i+"_loader'>\n</div>\n</div>\n<input type='hidden' id='"+i+"' name='"+i+"' "+tagv+" "+minl+" "+maxl+" />\n"; break; 
			case 'multilist': comp="<div class='fl'><select class='multilist' id='"+i+"_dest' name='"+i+"_dest' size='8' tabindex = '"+counter+"' title = '"+value.fieldName+"'></select>&nbsp;<img src='images/arrow_big.png' class='relation_starter absmiddle' id='"+i+"_relationstarter' alt='' /><br class='clearleft' /><button type='button' id='"+i+"_remove' class='button button-orange removefromlist' >"+lng.remove+"</button></div>\n"; 
			                  comp+="<div id='"+i+"_relationcontainer' class='fl relationcontainer'><div class='ploader' id='"+i+"_loader'>\n</div>\n</div>\n"; 
			                  comp+="<input type='hidden' "+tagv+" "+minl+" "+maxl+" id='"+i+"' name='"+i+"'  />\n"; break;
     		 case 'image': case "file": comp="<div><div class='button button-blue' id='"+i+"_' tabindex = '"+counter+"'>"+lng.load+"</div>\n";
			              comp+="<input type='text' "+tagv+" id='"+i+"' name='"+i+"' title = '"+value.fieldName+"' class='halfsize' readonly='readonly' />&nbsp;<img id='"+i+"_empty' class='d_empty' src='images/close-icon.png' alt='"+lng.deletecontent+"' /></div>\n";
			              comp+="<div class='clear'></div>\n"; 
			              comp+="<div id='"+i+"_holder' class='imageholder'></div>\n"; break;
			case 'bool':  comp="";
			        var cont=1;
                    $.each(value.values, function(vkey, vvalue) {
                        var ssel=(cont==1) ? "checked" : "";
	                    comp+="<input type='radio' "+tagv+" id='"+i+vkey+"' name='"+i+"' class='checkbox' value='"+vkey+"' title = '"+value.fieldName+"' "+ssel+" />&nbsp;<span class='checkboxtxt'>"+vvalue+"</span>";               
	                    cont++;   
			         }); break;
		    case 'coords': comp="<input type='text' "+tagv+" id='"+i+"' name='"+i+"'/><button id='address-submit-"+i+"' class='button button-blue fl' type='button'>"+lng.search+"</button><div id='"+i+"_holder' class='googlemaps'></div>\n"; break;
		}
		if (table_actual.fieldHints.hasOwnProperty(i))
        	comp+="<div class='advice'>"+table_actual.fieldHints[i]+"</div>\n";		
		counter++;
		var ddinit = "<dd id='"+ddid+"' "+rowstyl+ddestilo+">";
		var ddfin = "</dd>";
		$('#formFields').append((value.kindof!="hidden") ? labl+ddinit+comp+ddfin : comp);
	});

	if (objectSize(table_actual.relationFields) > 0) {
		for(i in table_actual.relationFields) { 
			fillFormField(i,'','',0,1);
		}
	}
}

//fill the fields of the edition form with a record data
function doedit(id) {
	switchForm();
	clearForm();
	$.each(filepointers, function(v){
     v.submited=false;
  });
  var fields=kindofFields();
  var editconf={ table: table_actual.table, 
                 keyfield: table_actual.keyfield, 
				         op: 'e',
				         id: id,
				         fields:fields,
				         relations:table_actual.relationFields          
				        }; 
  loaderMain('block');				        
	$.ajax({
    url: 'ajax/dbdata.php',
    type: 'POST',
    data: { postdata:JSON.stringify(editconf) }, 
    success: function(msg){
    	var jsResp=JSON.parse(msg);
    	tempfieldsholder={};
   		$.each(jsResp[0], function(i, value) {
       if (i==table_actual.keyfield) {
         fillfields_conf(value);
       }
   		 else if (table_actual.fields.hasOwnProperty(i)) {
   		 	   formFieldSet(i,table_actual.fields[i],value);
        }
 	    });
    loaderMain('none');
    }
  });
}

//to delete a record
function dodelete(id) {
  if (confirm(lng.wantdelete)) {
  var dfile=null;
  if (table_actual.istherekindof("image") || table_actual.istherekindof("file")) {
    dfile={};
    $.each(table_actual.fields, function(i, value) {  
      if ((value.kindof=='image') || (value.kindof=='file')) {
        var conthumb=value.hasOwnProperty("createthumb");
        dfile[i]={ uploaddir:value.uploaddir, thumb:conthumb };
      }
    });
  }
  var deleteconf={ table: table_actual.table, 
                   keyfield: table_actual.keyfield, 
				           op: 'd',
				           id: id,
				           files: dfile         
				        }; 
	$.ajax({
    url: 'ajax/dbdata.php',
    type: 'POST',
    data: { postdata:JSON.stringify(deleteconf) }, 
    success: function(msg){
    	showStatus(lng.recorddeleted,5000);
      dolist();
    }
  });
 }
}

//this function is used to fill the form field that holds a "list" or "multilist" data type (a type that has a relation with another table)
//we need to query for all the records of the other table to fill the form field. 
//If we do not need all the records of the other table, we can specifiy conditionals to retrieve only a group of records.
//Refer to the config documentation, the 'relationConditionals' Table property.
function fillFormField(key,search,field,fieldvalue,page) {
   var relation_props=table_actual.relationFields[key];
   var strings=new Array(lng.prevText,lng.nextText,lng.filter);
   if (relation_props.hasOwnProperty("static_array")) {
     var keys=new Array();
     var data=new Array();
     $.each(relation_props.static_array, function(i, value) { 
    		  keys.push(i);
    		  data.push(value);
   	  });
     $("#"+key+"_loader").load("includes/relationloader.php", {key:key, 'keys[]':keys, 'data[]':data, 'strings[]':strings, page:page, search:search });
   } else {
     var relations=[relation_props.table,relation_props.relationField,relation_props.substField];
     $("#"+key+"_loader").load("includes/relationloader.php", {field:field, fieldvalue:fieldvalue, key:key, 'relation_props[]':relations, 'strings[]':strings, page:page, search:search });
   }
}

function refreshVal(field,key,value) {
  var kindof=table_actual.fields[field].kindof;
  if (kindof=="list") {
    $("#"+field).val(key);
    $("#"+field+'_holder').val(value);
    
    var relation_props=table_actual.relationFields[field];
    if (relation_props.hasOwnProperty("chainedWith")) {
      var chained_props=table_actual.relationFields[relation_props.chainedWith];
      fillFormField(relation_props.chainedWith,'',"id"+field,key,1);
    }
     
  } else if (kindof=="multilist") {
    var found=false;
    $('#'+field+'_dest option').each(function(i, element){
	 	if ($(element).val()==key) {
	 	  found=true;
	 	  return false;
	 	}
    });
    if (!found)
       $('#'+field+'_dest').append("<option value="+key+">"+value+"</option>"); 
  }  
}

//Fill the listing filter list with the names of the actual table fields, so we can filter for all of them
function fillSearchList(list) {
	 $.each(table_actual.fields, function(i, value) {
	 	  if ((value.kindof!="multilist") && (value.kindof!="hidden")) //we can't search by a multilist field in this version, and not in a hidden one
	 	    $('#'+list).append("<option value="+i+">"+value.fieldName+"</option>"); 
	});
}

//Fill the filter string list with values of the selected field of the current table
function fillWhatSearchList(list_org,list) {
var field=$('#'+list_org).val();
var typeoffield=table_actual.fields[field].kindof;
if ((typeoffield != 'tinymce') && (typeoffield != 'textarea')) {
if (field.length > 0) {
  var searchconf={       table: table_actual.table, 
                         field: field,
				         kindof: table_actual.fields[field].kindof,
				         relations:table_actual.relationFields
   }; 
	$.ajax({
    url: 'ajax/fieldvalues.php',
    type: 'POST',
    data: { postdata:JSON.stringify(searchconf) }, 
    success: function(msg){
    	var jsResp=JSON.parse(msg);
    	 $('#'+list+" option").remove();
    	 $.each(jsResp, function(key,value) {
    	   $('#'+list).append("<option value="+key+">"+eval("value."+field)+"</option>"); 
    	 });
    }
  });
  }
 }
}

//When we save a form to the database, we send to the ajax php script all the information about the actual table
function fillfields_conf(value) {
  editidvalue=value;
  var fields=kindofFields();
	var fields_conf={ tablename: table_actual.table, 
                    keyfield: table_actual.keyfield, 
				            idnumber: value, 
				            dateformat: generalConfig.dateformat,
				            relations: table_actual.relationFields,
				            fields: fields  
				          }; 			  	 
 	$("#fieldsconfig").val(JSON.stringify(fields_conf));
}

//The 'tempfieldsholder' var is used to hold a copy of all the fields data before filling the editing form, so when we click the "save form" button
// we compare the actual data with the saved data and only send to the database the fields that have been changed, not all.
function refreshtempfieldsholder(formdata) {
	$.each(formdata, function (i,v) {
	   if (i>0) tempfieldsholder[v.name]=v.value; ////bypass the hidden config value
	 });
}

//This function resizes a big image to show it in the edition form
function imageresizeonload(imageholder, imagename, max_width) {
	var img = new Image();
  $(img).load(function () {
      setTimeout(function(){
      $(img).hide();
      var width = img.width;
		  var height = img.height;
		  if (width > max_width) {
			 			var ratio = (height / width);
			      var new_width = max_width;
			      var new_height = (new_width * ratio);
			      //Shrink the image and add link to full-sized image
			      $(img).height(new_height).width(new_width);
  	   }
      $(imageholder).removeClass('imageloading').append(img);
      $(img).fadeIn();
      },50);
    }).error(function () {
      setTimeout(function(){
    	  $(imageholder).removeClass('imageloading').html(lng.noimageavailable);
    	},50);
       }).attr('src', imagename).addClass('photo');
}

//gives the correct display format to different types of data
function formatDates(value,kindof) {
 var result;
 if (!value) result=value;
 else {
  switch(kindof) {
 	 case "datetime": result=mysqlDateTimeToDateTime(value,generalConfig.dateformat); break;
 	 case "date": result=mysqlDateToDate(value,generalConfig.dateformat); break;
 	 case "time": result=value.substr(0,value.length-3); break;
  }
 }
 return result;
}

//Field value formatting depending on its type
function formFieldSet(field,properties,value) {
	  switch(properties.kindof) {
	  case "image": $("#"+field).val(value); 
                  if (value) { 
                   	 $("#"+field+"_holder").addClass('imageloading');
                        	 imageresizeonload("#"+field+"_holder", properties.uploaddir+'/'+value, 500);
                  } else {
                  	 $('#'+field+'_holder').html(''); $('input[name='+field+'_]').val('');
                  }
                  tempfieldsholder[field]=value; 
                  break;
    case "file": $("#"+field).val(value); 
                 if (value) 
                    $("#"+field+"_holder").html('<a href="'+properties.uploaddir+'/'+value+'" target="_blank" ><img src="images/file.gif" alt="" /></a>'); 
                 else {
                 	  $('#'+field+'_holder').html(''); $('input[name='+field+'_]').val('');
                 }
                 tempfieldsholder[field]=value; 
                 break;                          
    case "tinymce":  tinyMCE.get(field+"_").setContent(value); 
                    tempfieldsholder[field]=value; break;
    case "bool": $.each(table_actual.fields[field].values, function (ki,kv) { 
                    if (value==ki) {
                      $("#" + field+ki).attr('checked', true);
                      return false; 
                    }
                 });
                 tempfieldsholder[field]=value; 
                 break;
    case "datetime": case "date": case "time": $("#" + field).val(formatDates(value,table_actual.fields[field].kindof)); 
                                               tempfieldsholder[field]=formatDates(value,table_actual.fields[field].kindof); 
                     break;
    case "list":   if (value) {
                      $("#"+field+'_holder').val(value); 
                      $("#"+field).val(value); 
                      tempfieldsholder[field]=value;
                    }
                    else {
                        $("#"+field).val('');
                    	$("#"+field+'_holder').val('');
                    	tempfieldsholder[field]='';
                    }
                    break;
    case "multilist": if (value) {
                       tempfieldsholder[field]="";
                       var searchconf={       
                         value: value,
				         relations:table_actual.relationFields[field]
                       };
                       $.ajax({
                          url: 'ajax/somefieldvalues.php',
                          type: 'POST',
                          data: { postdata:JSON.stringify(searchconf) }, 
                          success: function(msg){
                            var jsResp=JSON.parse(msg);
    	                    $('#'+field+'_orig option').remove();
    	                    $.each(jsResp, function(key,value) { 
    	                      $('#'+field+'_dest').append("<option value="+value['key']+">"+value['value']+"</option>"); 
    	                      tempfieldsholder[field]+=value['key']+",";
    	                    });
    	                    tempfieldsholder[field]=tempfieldsholder[field].substr(0,tempfieldsholder[field].length-1);
                          }
                       });
                      }
                      else {
                      	$('#'+field+'_dest option').remove();
                      	tempfieldsholder[field]=value;
                      }
                     break;
    case "password" :if (value) value='md5'; 
                     $("#" + field).val(value); tempfieldsholder[field]=value;
                     break; 
    case "coords" :  $("#" + field).val(value);
    				 var rcoords=(value) ? value.split(",") : [41.659,-4.714];
    				 var latlng = new google.maps.LatLng(rcoords[0],rcoords[1]);
  					 var options = {
    					zoom: 16,
    					center: latlng,
   						mapTypeId: google.maps.MapTypeId.ROADMAP
  					  };
  					 var map = new google.maps.Map(document.getElementById(field+"_holder"), options);
  					 var geocoder = new google.maps.Geocoder();
  					 table_actual.fields[field].map=map;
  					 table_actual.fields[field].geocoder=geocoder;
  					 if (value) {
  					   table_actual.fields[field].marker=newMarker(map,latlng,geocoder,field);
  					 }
  					 
    				break;                                    
    default: $("#" + field).val(value); tempfieldsholder[field]=value; 
    }
}

function newMarker(map,position,geocoder,field) {
 var marker = new google.maps.Marker({
			   	position: position,
				map: map,
				draggable: true
 });
 google.maps.event.addListener(marker, 'drag', function() {
    	geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
    		if (results[0]) {
    		  $("#"+field).val(marker.getPosition().lat()+","+marker.getPosition().lng());
            }
	    }
	 });
  });
  return marker;
}

function addressQuery(field) {
  var query = $("#"+field).val();
  if (/\s*^\-?\d+(\.\d+)?\s*\,\s*\-?\d+(\.\d+)?\s*$/.test(query)) {
    var latlng = parseLatLng(query);
    if (latlng == null) {
      $("#"+field).val('');
    } else {
      geocode({ 'latLng': latlng },field);
    }
  } else {
    geocode({ 'address': query },field);
  }
}

function parseLatLng(value) {
  value.replace('/\s//g');
  var coords = value.split(',');
  var lat = parseFloat(coords[0]);
  var lng = parseFloat(coords[1]);
  if (isNaN(lat) || isNaN(lng)) {
    return null;
  } else {
    return new google.maps.LatLng(lat, lng);
  }
}

function geocode(request,field) { 
  var bounds = new google.maps.LatLngBounds();
  if (table_actual.fields[field].marker)
    table_actual.fields[field].marker.setMap(null);
  if (request.latLng) {
    table_actual.fields[field].marker = newMarker(table_actual.fields[field].map,request.latLng,table_actual.fields[field].geocoder,field);
    bounds.extend(request.latLng);
    table_actual.fields[field].map.fitBounds(bounds);
  } else { 
  var language = generalConfig.googlemaps_lng;
  if (language) {
    request.language = language;
  }
  table_actual.fields[field].geocoder.geocode(request, function(results, status) {
           if (status == google.maps.GeocoderStatus.OK) {
             table_actual.fields[field].marker = newMarker(table_actual.fields[field].map,results[0].geometry.location,table_actual.fields[field].geocoder,field);
   			  bounds.extend(results[0].geometry.location);
              table_actual.fields[field].map.fitBounds(bounds);		 
             $("#"+field).val(results[0].geometry.location.lat()+","+results[0].geometry.location.lng());
           }
        })
   }    
}

//function to load css files dynamicly
function loadCss(url) 
{	
	var head = document.getElementsByTagName("head")[0];
	var script = document.createElement("link");
	$(script).attr({type: 'text/css', href: url, rel: 'stylesheet', media: 'screen'});
	script.onload = script.onreadystatechange = function(){};
	head.appendChild(script);
}

//This function loads the semi-transparent curtain that appears when an Ajax query is running
function loaderMain(val) {
  if (val=='block')
    $(document).mask({closeSpeed:100, loadSpeed:100});
  else $.mask.close();
}

//This function gives the fields and its type in a single assoc array
function kindofFields() {
  var arrfinal={};
  $.each(table_actual.fields, function(i, value) {
	 	  arrfinal[i]=value.kindof; 
	});
	return arrfinal;
}

function showStatus(message,timeout)
{
   if ($("#editing").css('display')=="block")
		$("#status_edit").html(message);   
   else $("#status_list").html(message);		
   if (timeout) 
     setTimeout(closeStatus,timeout);
}

function closeStatus()
{
   if ($("#editing").css('display')=="block")
		$("#status_edit").html('');   
   else $("#status_list").html('');
}

