////////////////////////////////////////////////////
// Conciliación: gestión de conciliación de activos
// Version: 1.0
//
// Copyright (C) 2014  Eustotem Multimedia, S.L.
//
// License: MIT, see LICENSE
////////////////////////////////////////////////////


function openFilePopup(control,resId,subType,maxSize){
	var url="upload_popup2.php?control="+control+"&resId="+resId+"&subType="+subType+"&maxSize="+maxSize;
	$('<a href="'+url+'">file popup</a>').fancybox({
		overlayColor:'#000', padding:0,
		autoScale:false, width:350, height:100,
		transitionIn:'none', transitionOut:'none',
		type:'iframe', autoDimensions:false
	}).click();
}
function openFileImportPopup(control,resId,subType,maxSize){
	var url="upload_popup4.php?control="+control+"&resId="+resId+"&subType="+subType+"&maxSize="+maxSize;
	$('<a href="'+url+'">file popup</a>').fancybox({
		overlayColor:'#000', padding:0,
		autoScale:false, width:350, height:100,
		transitionIn:'none', transitionOut:'none',
		type:'iframe', autoDimensions:false
	}).click();
}
function openFileServerPopup(control,resId,subType,maxSize,rootfolder){
	var url="upload_popup3.php?control="+control+"&resId="+resId+"&subType="+subType+"&maxSize="+maxSize+"&rootfolder="+rootfolder;
	$('<a href="'+url+'">file popup</a>').fancybox({
		overlayColor:'#000', padding:0,
		autoScale:false, width:900, height:600,
		transitionIn:'none', transitionOut:'none',
		type:'iframe', autoDimensions:false
	}).click();
}
function _openFilePopup(control,resId,subType,maxSize){
	openPopupWindow("upload_popup.php?control="+control+"&resId="+resId+"&subType="+subType+"&maxSize="+maxSize,"upload",350,100,true);
}
function openImgProcPopup(control,resId,subType,maxSize,w,h){
	openPopupWindow("imgproc_popup.php?control="+control+"&resId="+resId+"&subType="+subType+"&maxSize="+maxSize,"upload",w,h,true);
}

function deleteFile(param){
	document.getElementById(param+"_caption").innerHTML="Archivo actual: [vacío]";
	document.getElementById(param+"_delete").style.display="none";
	document.getElementById(param).value="";	// este valor no se puede admitir como valor de archivo
}

function updateFileControl(control,value){
	document.getElementById(control+"_caption").innerHTML="Archivo actual: <strong>" + value + "<\/strong> <em>(temp)<\/em>";
	document.getElementById(control+"_delete").style.display="inline";
	document.getElementById(control).value=value;
}



var mapas={};
function createMap(field, data){
	var temp=data.split(",");
	var numeros=true;
	for(var i=0;i<temp.length;i++){
		if(isNaN(temp[i])){
			numeros=false; break;
		}
	}
	var myOptions = {
		streetViewControl: false, scaleControl: true, mapTypeControl: true,
		mapTypeControlOptions: {
			style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
		},
	 	navigationControl: true,
		navigationControlOptions: {style: google.maps.NavigationControlStyle.DEFAULT},
		mapTypeId: google.maps.MapTypeId.ROADMAP 
	}
	if(numeros==true){
		myOptions.zoom=parseInt(temp[2]);
		myOptions.center=new google.maps.LatLng(parseFloat(temp[0]),parseFloat(temp[1]));
		renderMap(field, data, myOptions);
	}else{
		var geocoder = new google.maps.Geocoder();
		var addr=temp.join(",");
		geocoder.geocode( { 'address': addr}, function(results, status) {
			switch(status){
				case google.maps.GeocoderStatus.OK:
					myOptions.zoom=8;
					myOptions.center=results[0].geometry.location;
					break;
				case google.maps.GeocoderStatus.ZERO_RESULTS:
					myOptions.zoom=parseInt(5);
					myOptions.center=new google.maps.LatLng(40.527197544367745,-3.7854440999999506);
					break;
			}
			renderMap(field, data, myOptions);
		});
	}
}
function renderMap(field, data, myOptions){
	mapas[field].map = new google.maps.Map(document.getElementById(field+"_map_canvas"),myOptions);
	google.maps.event.addListener(mapas[field].map, 'zoom_changed', function() {changeMapZoom(field);mapChanged(field);});                       
	google.maps.event.addListener(mapas[field].map, 'center_changed', function() {changeMapCoords(field);mapChanged(field);});                       
}
function updateMapControls(field){
	var map=mapas[field].map, data=mapas[field].data, temp=data.split(",");
	var zoom=map.getZoom(), lat=map.getCenter().lat(), lon=map.getCenter().lng();
	var tipo=document.getElementById(field+"_map_type").className;
	document.getElementById(field).value=lat+","+lon+","+zoom+","+(tipo=="btn_spot" ? "1" : "2");
	document.getElementById(field+"_str").value=document.getElementById(field).value;
}
function mapChanged(field){
	var ch=document.getElementById(field+"_map_get");
	ch.className="btn_warning";
}
function changeMapCoords(field){
	var map=mapas[field].map, data=mapas[field].data, temp=data.split(",");
	temp[0]=map.getCenter().lat();
	temp[1]=map.getCenter().lng();
	mapas[field].data=temp.join(",");
	updateMapControls(field);
}
function changeMapZoom(field){
	var map=mapas[field].map, data=mapas[field].data, temp=data.split(",");
	temp[2]=map.getZoom();
	mapas[field].data=temp.join(",");
	updateMapControls(field);
}
function toggleMapMarkerType(field){
	var el=document.getElementById(field+"_map_crosshair");
	var bu=document.getElementById(field+"_map_type");
	el.className=el.className=="map_crosshair" ? "map_area" : "map_crosshair";
	bu.className=bu.className=="btn_spot" ? "btn_area" : "btn_spot";
	
	var map=mapas[field].map, data=mapas[field].data, temp=data.split(",");
	temp[3]=el.className=="map_crosshair" ? "1" : "2";
	mapas[field].data=temp.join(",");
	mapChanged(field);
	updateMapControls(field);
}
function resetMap(field,original){
	var datos=original.split(","), map=mapas[field].map;
	mapas[field].data=original;
	map.setCenter(new google.maps.LatLng(parseFloat(datos[0]),parseFloat(datos[1])));
	updateMapControls(field);
	map.setZoom(parseInt(datos[2]));
	var ch=document.getElementById(field+"_map_get");
	ch.className="btn_ok";
	var aa=document.getElementById(field+"_map_crosshair");
	aa.className=datos[3]=="1" ? "map_crosshair" : "map_area";
	var bb=document.getElementById(field+"_map_type");
	bb.className=datos[3]=="1" ? "btn_spot" : "btn_area";
	grabMapData(field);
}
function grabMapData(field){
	var el=document.getElementById(field+"_str");
	el.value=mapas[field].data;
	var ch=document.getElementById(field+"_map_get");
	ch.className="btn_ok";
}

function fixCoords(lat,lon,field){
	var valor=lat+"{@@@}"+lon;	
	var control=document.getElementById(field);
	control.value=valor;
}


function getPassStr(control){
	var valor=control.value, fuerza=0;
	var reMin = new RegExp("[a-z]"), reMay = new RegExp("[A-Z]"), reDig = new RegExp("[0-9]");
	if(valor.length>6) fuerza++;
	if(valor.length>9) fuerza++;
	if(valor.match(reMin)) fuerza++;
	if(valor.match(reMay)) fuerza++;
	if(valor.match(reDig)) fuerza++;
	$("#"+control.id+"_marca").text(fuerza+"/5");
}
function enableSecondaryField(param){
	var control=$("#"+param+"_2").get(0);
	var check=$("#"+param+"_check").get(0);
	if(!check.checked){
		control.disabled=false;
		control.style.opacity=1;
	}else{
		control.value="";
		control.disabled=true;
		control.style.opacity=.5;
	}
}



function initRelatedSelect(resId, control, valor){
	var yuyu='select[class*="rel_'+control+'"]';
	$(yuyu).attr("disabled","disabled");
	getRelatedSelectData(resId, control, valor, 0);
	$(yuyu).change(function(){
		$("#"+control).val($(this).val());
		var num=$(yuyu).toArray().length;
		current=parseInt($(this).attr("id").split(control).join(""));
		if(num==current) return;
		for(var i=current+1; i<=num; i++){
			$("#"+control+i).attr("disabled","disabled").find('option[value!="-1"]').remove();
		}
		if($(this).val()!="-1") $("#"+control+(current+1)).addClass("glow_red");	
		getRelatedSelectData(resId, control, $(this).val(), current);
	});
}
function getRelatedSelectData(resId, control, valor, despl){
	$.ajax({
		url: "../core/XHR.relatedselects.php", dataType: "json", data: {action:'init', resId:resId, valor:valor, control:control},
		success: function(data){
			$(".glow_red").removeClass("glow_red");
			if(data.result=="OK"){
				$.each(data.data, function(indice){
					var arr=data.data[indice+despl];
					var sel=$("#"+control+(indice+1+despl));
					$.each(arr, function(key, value){
						sel.append($("<option></option>").attr("value",value.value).text(value.label));
						sel.removeAttr("disabled");
						if(value.value==data.breadcrumb[indice]) sel.val(value.value);
					});
				});
			}else{
			}
		}
	});
}



function initButtonset(control_orig, lng, editor){
	$('#'+control_orig+'_radio').buttonset();
	
	var changeLangMethod=editor ? changeLangEd : changeLang;
	var writeLangMethod=editor ? writeLangEd : writeLang;
	
	$('input[id^="'+control_orig+'_b_"]').click(function(event){ changeLangMethod($(this).attr('id')); });
	$('#'+control_orig).change(function(){ writeLangMethod(control_orig); });
	
	$('#'+control_orig+'_b_'+lng).trigger('click');
}
function changeLang(control_id){
	var temp=control_id.split("_b_");
	var control_orig=temp[0], hidden_id=temp.join("_h_");	
	$('#'+control_orig).val($('#'+hidden_id).val());
	$('#'+control_orig).focus();
}
function writeLang(control_name){
	var temp=$('#'+control_name+'_radio :radio:checked');
	var control_dest=temp.attr('id').split('_b_').join('_h_');
	$('#'+control_dest).val($('#'+control_name).val());
}
function changeLangEd(control_id, idio){
	var temp=control_id.split("_b_");
	tinyMCE.execInstanceCommand(temp[0],'mceSetContent',false,$('#'+temp[0]+'_h_'+temp[1]).val(),true);
}
function writeLangEd(inst){
	try{
		var control_name=inst.getElement().id;
		var control_radio=$('#'+control_name+'_radio :radio:checked').attr('id');
		var control_hidden=control_radio.split('_b_').join('_h_');
		$('#'+control_hidden).val(inst.getContent());
	}catch(e){}
}



function date_mysql2js(param){
	var date = new Date();
	var parts = String(string).split(/[- :]/);
	date.setFullYear(parts[0]);
	date.setMonth(parts[1] - 1);
	date.setDate(parts[2]);
	date.setHours(parts[3]);
	date.setMinutes(parts[4]);
	date.setSeconds(parts[5]);
	date.setMilliseconds(0);
	return date;
}
function date_js2mysql(tipo, date){
	var ret;
	switch(tipo){
		case "date":
			ret=date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate();
			break;
		case "datetime":
			ret=date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
			break;
		case "time":
			var d=new Date();
			ret=d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate()+" "+date[0].value;
			break;
	}
	return ret;
}



function updSelect(source,target){
	var l=source.options.length;
	var el=document.getElementById(target);
	var cadena="";
	var obj=new Object();
	for(i=0;i<source.options.length;i++){
		if(source.options[i].selected){
			obj["opt_"+source.options[i].value]="selected";
		}
	}
	el.value=JSON.stringify(obj);
}



(function( $ ) {
	$.widget( "ui.combobox", {
		_create: function() {
			var input,
				self = this,
				select = this.element.hide(),
				selected = select.children( ":selected" ),
				value = selected.val() ? selected.text() : "",
				myname=this.element[0].getAttribute('id');
				mystyle=this.element[0].getAttribute('class').split('animated select_editable').join('');
				wrapper = this.wrapper = $( "<span>" )
					.addClass( "ui-combobox" )
					.insertAfter( select );

			input = $( "<input>" )
				.appendTo( wrapper )
				.val( value )
				.attr('name', myname)
				.addClass( "ui-state-default ui-combobox-input " + mystyle )
				.autocomplete({
					delay: 0,
					minLength: 0,
					source: function( request, response ) {
						var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
						response( select.children( "option" ).map(function() {
							var text = $( this ).text();
							if ( this.value && ( !request.term || matcher.test(text) ) )
								return {
									label: text.replace(
										new RegExp(
											"(?![^&;]+;)(?!<[^<>]*)(" +
											$.ui.autocomplete.escapeRegex(request.term) +
											")(?![^<>]*>)(?![^&;]+;)", "gi"
										), "<strong>$1</strong>" ),
									value: text,
									option: this
								};
						}) );
					},
					select: function( event, ui ) {
						ui.item.option.selected = true;
						self._trigger( "selected", event, {
							item: ui.item.option
						});
					},
					change: function( event, ui ) {
						if ( !ui.item ) {
							var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
								valid = false;
							select.children( "option" ).each(function() {
								if ( $( this ).text().match( matcher ) ) {
									this.selected = valid = true;
									return false;
								}
							});
							if ( !valid ) {
								$( this ).val( "" );
								select.val( "" );
								input.data( "autocomplete" ).term = "";
								return false;
							}
						}
					}
				})
				.addClass( "ui-widget ui-widget-content ui-corner-left" );

			input.data( "autocomplete" )._renderItem = function( ul, item ) {
				return $( "<li></li>" )
					.data( "item.autocomplete", item )
					.append( "<a>" + item.label + "</a>" )
					.appendTo( ul );
			};
			input.val( $(select).find("option:selected").text());

			$( "<a>" )
				.attr( "tabIndex", -1 )
				.attr( "title", "Show All Items" )
				.appendTo( wrapper )
				.button({
					icons: {
						primary: "ui-icon-triangle-1-s"
					},
					text: false
				})
				.removeClass( "ui-corner-all" )
				.addClass( "ui-corner-right ui-combobox-toggle" )
				.click(function() {
					if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
						input.autocomplete( "close" );
						return;
					}

					$( this ).blur();

					input.autocomplete( "search", "" );
					input.focus();
				});
		},

		destroy: function() {
			this.wrapper.remove();
			this.element.show();
			$.Widget.prototype.destroy.call( this );
		}
	});
})( jQuery );


