/*!
 *
 * 	Ubica tu Casilla -- IFE
 *	Funciones Generales
 * 	spaiks4@gmail.com
 *	08-06-11
 * 
 */

function key_validate(e){
	if(e.keyCode == 13){
		get_valores();
	}
}
function remplaza(v1,v2,txt){
	// ! Remplaza el v1 por el v2 en txt
	var tmp = txt;
	while (tmp.indexOf(v1)>-1){
		var p = tmp.indexOf(v1);
	    tmp = "" + (tmp.substring(0, p) + v2 + tmp.substring((p + v1.length), tmp.length));
	}
	return tmp;
}
function mvolador_show(img,html,t,telon){
	if(telon){
		$("#mtelon").fadeIn("fast");
	}
	if(img == null){
		var x_html = '<div class="limpiar"></div>';
		x_html += '<p class="mv-texto">'+html+'</p>';
		x_html += '<div class="limpiar"></div>';
		$('#mvolador').html(x_html);
		var aux_h_vm = $('#mvolador').height();
		var aux_hm_vm = 0;
		if(aux_h_vm < h__){
			aux_hm_vm = (h__ - aux_h_vm) / 2;
		}else{
			aux_hm_vm = 0;
			
		}
		$('#mvolador').css('top',aux_hm_vm);
		$("#mvolador").fadeIn("slow");
	}else{
		var dir_img = 'img/'+img;
		var x_html = '<div class="limpiar"></div>'
		x_html += '<div class="mv-img"><img src="'+dir_img+'" border="0" /></div>';
		x_html += '<p class="mv-texto" style="margin:0;">'+html+'</p>';
		x_html += '<div class="limpiar"></div>';
		$('#mvolador').html(x_html);
		var aux_h_vm = $('#mvolador').height();
		var aux_hm_vm = 0;
		if(aux_h_vm < h__){
			aux_hm_vm = (h__ - aux_h_vm) / 2;
		}else{
			aux_hm_vm = 0;
			
		}
		$('#mvolador').css('top',aux_hm_vm);
		$('#mvolador').fadeIn('slow');
	}
	if(t > 0){
		setTimeout(mvolador_hide,t);
	}
}
function mvolador_hide(){
	$('#mtelon').fadeOut('fast');
	$('#mvolador').fadeOut('fast');
}
function mvoladorcfg_hide(){
	$('#mvoladorcfg').fadeOut('fast');
}
function get_ajax_call(url,callback){
	// ! Manda llamar un ajax obtiene su respuesta y si es done manda llamar una funcion dada
	var aux_url = url.split('?');
	$.ajax({
		url: aux_url[0],
		data: aux_url[1],
		dataType: "html",
		cache:false,
		type: "POST",
		beforeSend: function(){
			mvolador_show('uc2-loader.gif','<b>Cargando</b>, Espere Por Favor...',0,true);
		},
		success: function(txt){
			mvolador_hide();
			if(callback != 'null'){
				eval(callback + '(\''+txt+'\')');
			}
        },
		error: function(txt, info, otro){
			mvolador_hide();
			mvolador_show('uc2-error.png','<b>Error...</b><br />'+ info,4000,false);
		}
	});
}
function get_ajax_call_noasync(url,callback){
	// ! Manda llamar un ajax obtiene su respuesta y si es done manda llamar una funcion dada
	var aux_url = url.split('?');
	$.ajax({
		url: aux_url[0],
		data: aux_url[1],
		dataType: "html",
		async: false,
		cache:false,
		type: "POST",
		beforeSend: function(){
			mvolador_show('uc2-loader.gif','<b>Cargando</b>, Espere Por Favor...',0,true);
		},
		success: function(txt){
			mvolador_hide();
			if(callback != 'null'){
				eval(callback + '(\''+txt+'\')');
			}
        },
		error: function(txt, info, otro){
			hide_loading();
			mvolador_show('uc2-error.png','<b>Error...</b><br />'+ info,4000,false);
		}
	});
}
function fill_estados(){
	var i = 1;
	var array = new Array();
	for(i = 1; i < estados__.length;i++){
		var v1 = estados__[i].id;
		var v2 = estados__[i].nombre;
		var aux = v1 + '|' + v2;
		array[array.length] = aux;
	}
	put_select('estados',array);
}
function put_select(id,array){
	// ! llena un combo con el array el primer valor del array es el id el segundo el valor es el text
	// * necesita un array con sus contenidos separados por |
	var select_ = document.getElementById(id);
	select_.innerHTML = '';
	if(array.length <= 0){
		var opc_ = document.createElement('option');
		opc_.value = '0';
		opc_.text = 'Sin Opciones';
		select_.options.add(opc_);
	}else{
		var opc_ = document.createElement('option');
		opc_.value = '0';
		opc_.text = 'Elige una opción';
		select_.options.add(opc_);
	}
	for(var i = 0; i < array.length; i++){
		var opc_ = document.createElement('option');
		var aux = array[i].split('|');
		opc_.value = aux[0];
		opc_.text = aux[1];
		select_.options.add(opc_);
	}
	select_.selectedIndex = 0;
}
function get_point_coordenadas(coordenada){
	// ! Convierte una cadena de texto por un tipo punto
	var tmp = coordenada.split(',');
	var val1 = tmp[0];
	var val2 = tmp[1];
	//alert(val1 + '\n' + val2);
	var punto = new google.maps.LatLng(val1,val2);
	return punto;
}
function limpiar_markers(){
	if(list_objets__.length > 0){
		var i = 0;
		for(i = 0; i < list_objets__.length; i++){
			list_objets__[i].setIcon('/img/uc2-casilla-off.png');
		}
	}
}
function clear_map(){
	clear_infowindow();
	if(list_objets__.length > 0){
		var i = 0;
		for(i = 0; i < list_objets__.length; i++){
			list_objets__[i].setMap(null);
		}
		list_objets__.length = 0;
		bounds__ = new google.maps.LatLngBounds();
	}
}
function clear_infowindow(){
	if(list_objets__.length > 0){
		var i = 0;
		for(i = 0; i < list_objets__.length; i++){
			if(list_objets__[i].infowindow){				
				list_objets__[i].infowindow.close();
			}
		}
	}
}
function set_center(p,z){
	map__.setCenter(p);
	map__.setZoom(z);
}
function clear_str(str){
	var return_ = str;
	str = remplaza('&','Ñ',str);
	str = remplaza('$','Ü',str);
	str = remplaza('%','Ñ',str);
	return_ = str;
	return return_;
}
function click_to_check(nombre,opc){
	var name = '#box-check-' + nombre;
	var aux_valor = $(name + ' :input').val();
	var arr_valor = aux_valor.split('|');
	var opc_click = true;
	if(arr_valor[0] != null && arr_valor[0] != undefined && arr_valor[0] != ''){
		var aux = arr_valor[0];
		var tmp = '';
		var str = '|';
		var n = arr_valor.length;
		for(var i = 1; i < n; i++){
			str += tmp + arr_valor[i];
			tmp = '|';
		}
		if(aux == 'true'){
			var val = 'false' + str;
			$(name).removeClass('box-check-hover');
			$(name + ' :input').val(val);
			$(name + ' p').removeClass('check_checked');
			$(name + ' p').addClass('check_unchecked');
			opc_click = false;
		}else{
			var val = 'true' + str;
			$(name).addClass('box-check-hover');
			$(name + ' :input').val(val);
			$(name + ' p').removeClass('check_unchecked');
			$(name + ' p').addClass('check_checked');
		}
	}
	if(opc == '0'){
		click_c__ = opc_click;
	}else if(opc == '1'){
		toogle_casillas(nombre);
	}
}
function refill(valor,n){
	while(valor.length < n){
		valor = '0' + valor;
	}
	return valor;
}
function toogle_casillas(nombre){
	var name = '#' + nombre;
	var aux = $(name).val();
	var arr = aux.split('|');
	if(arr[1] != null && arr[1] != undefined && arr[1] != ''){
		var i = arr[1];
		var image = 'img/uc2-casilla-on.png';
		if(arr[0] == 'false'){
			image = 'img/uc2-casilla-off.png';
		}
		list_objets__[i].setIcon(image);
	}
}
function activar_efectos(){
	var m1 = $('#navigation').width();
	var m2 = $('#casillas').width() - 15;
	var m3 = $('#rutas').width() - 15;
	$('#casillas').hover(
		function () {
			$(this).stop().animate({'marginLeft':'-2px'},200);
		},
		function () {
			$(this).stop().animate({'marginLeft':'-'+m2.toString()+'px'},200);
		}
	);
	$('#rutas').hover(
		function () {
			$(this).stop().animate({'marginLeft':'-'+m3.toString()+'px'},200);
		},
		function () {
			$(this).stop().animate({'marginLeft':'0px'},200);
		}
	);
}
function put_ss_tooltip(){
	$('.tooltip').hover( 
		function (){  // Muestra
			var str_ = $(this).attr("rel");
			var tmp = str_.split('::');
			var title_ = tmp[0];
			var cnt_ = tmp[1];
			if(title_ == '' || title_ == null || title_ == undefined){
				title_ = '';
			}
			if(cnt_ == '' || cnt_ == null || cnt_ == undefined){
				cnt_ = '';
			}
			$("#ss-tooltip .ss-tooltip-title").html(title_);
			$("#ss-tooltip .ss-tooltip-cnt").html(cnt_);
			var p_ = $(this).position();
			var aux_left_ = p_.left;
			if((aux_left_ + $("#ss-tooltip").width()) >= w__){
				aux_left_ = w__ - ($("#ss-tooltip").width() + 10);
			}
			var aux_top_ = ($('#casillas').position().top + p_.top) - ($("#ss-tooltip").height() + 10);
			if(aux_top_ <= 0){
				aux_top_ = $(this).height() + 10;
			}
			$("#ss-tooltip").css('left',aux_left_);
			$("#ss-tooltip").css('top',aux_top_);
			$("#ss-tooltip").show(); 
		}, 
		function (){ // Oculta
			$("#ss-tooltip").hide();
		}
	);
}
function check_sv(cor,name){
	var point  = get_point_coordenadas(cor);
	name = '#' + name.toString();
	sv__.getPanoramaByLocation(point, 50, function(data, status){
			if(status == google.maps.StreetViewStatus.OK){
				$(name).css('display','block');
			}
		});
}
/*Funciones fenerales para traer valores ajax*/
function put_municipio(valor){
	var html = '<div class="v-cnt-box">';
	html += '<p class="v-box-title">' + valor + '<\/p>';
	html += '</div><div class="limpiar" style="height:1px;"></div>';
	$('#box_response').append(html);
}
function put_descripcion(v1,v2,v3,i){
	// ! coloca la lista de en la parte izquierda
	var name = i.toString();
	var html = '<div id="boxopcmap__' + name + '" class="v-cnt-box">';
	html += '<p class="v-box-text tooltip opc-map-casilla" rel="Casilla::'+v1+'" onclick="select_marker(\''+i+'\')">' + v1 + '<\/p>';
	html += '<p class="v-box-opc-map tooltip opc-map-ruta" rel="::¿Como llegar aquí?" onclick="put_msj_ruta(\''+i+'\')"><\/p>';
	html += '<p id="boxlist__'+name+'" class="v-box-opc-map tooltip opc-map-street" style="display:none;" rel="::Street View" onclick="put_street_view(\''+i+'\')"><\/p>';
	html += '</div><div class="limpiar" style="height:1px;"></div>';
	$('#box_response').append(html);
	var wt = $('#boxopcmap__' + name.toString()).width();
	var wa = $('#boxopcmap__' + name.toString() + ' .v-box-opc-map').width();
	var wf = wt - ((wa * 2) + 5);
	$('#boxopcmap__' + name.toString() + ' .v-box-text').width(wf);
	check_sv(v2,'boxlist__'+name);
}
function put_style_valor(i,v1,v2,v3,v4,v5,v6){
	var name = i.toString();
	var espacio = '<div class="limpiar" style="height:1px;"></div>';
	var tmp = '<p class="map_text">';
	tmp += 'La sección <b>' + v2 + '</b> cuenta con:<br />';
	var ac = v3.split(',');
	var ai = v4.split(',');
	var af = v5.split(',');
	for(var j = 0; j < ac.length; j++){
		var aux_ss = ac[j];
		if(aux_ss[0] != "S"){
			tmp += 'Casilla <b>' + ac[j] + '</b> que atiende a ciudadanos con apellido paterno que inicia con la letra <b>' + ai[j] + '</b> hasta la <b>' + af[j] + '</b><br />';
		}else{
			tmp += 'Casilla <b> Especial ' + aux_ss[1] + '</b><br />';
		}
		
	}
	tmp += '</p>' + espacio;
	tmp += '<div class="v-cnt-box">';
	tmp += '<p id="boxruta__' + name + '" class="opc-map-ruta-view" onclick="put_msj_ruta(\'' + i + '\')">¿Como llegar aquí?<\/p>';
	tmp += '<p id="boxstreet__' + name + '" class="opc-map-street-view" style="display:none;" onclick="put_street_view(\'' + i + '\')">Vista de calle<\/p>';
	tmp += '</div>';
	return tmp;
}
function put_style_text(valor){
	var tmp = '<p class="map_text">';
	tmp += valor + '<\/p>';
	return tmp;
}
function put_street_view(i){
	var point = list_objets__[i].getPosition();
	panorama__.setPosition(point);
	var toggle = panorama__.getVisible();
	if (toggle == false) {
      panorama__.setVisible(true);
    }
}
function put_msj_ruta(i){
	bounds__ruta__ = new google.maps.LatLngBounds();
	bounds__ruta__.extend(list_objets__[i].getPosition());
	restart_all();
	change_marker(i);
	var html = '<b>Esperando Ubicación ...</b><br />';
	html += '<span style="font-size:0.8em;">Si aparece en la ventana superior de tu navegador un mensaje, referente a tu ubicación, <i>oprime</i> el <i>botón</i> <i>aceptar</i> ó <i>permitir</i> y espera un momento...</span>';
	mvolador_hide();
	mvolador_show('uc2-loader.gif',html,0,true);
	id_marker_ruta__ = i;
	put_marker_ruta();
}
function put_marker_ruta(){
	var point = map__.getCenter();
	if(navigator.geolocation){
		// ! la funcion esperara 10 min hasta que el usuario acepte o niegue encontrar la posición
		navigator.geolocation.getCurrentPosition(function(position){
												// ! si encuentra la posición		  
													point = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
													put_m_ruta(point);
												},function(){
												// ! no encuentra la posicion	
													put_m_ruta(point);
												},{maximumAge:600000});
	}else{
		put_m_ruta(point);
	}
}
function put_m_ruta(p){
	mvolador_hide();
	var image = '/img/uc2-inicio.png';
	var shadow = '/img/shadow-uc2-inicio.png';
	if(marker_ruta__ == null){
		marker_ruta__ = new google.maps.Marker({
		    position: p,
		    map: map__,
			icon: image,
			shadow: shadow,
			draggable: true,
			title:'De aquí'
		});
		google.maps.event.addListener(marker_ruta__, 'dragend', function(){
			if(bandera_ruta__){
				calcular_ruta();
			}
		});
		bounds__ruta__.extend(p);
		map__.fitBounds(bounds__ruta__);
	}else{
		marker_ruta__.setPosition(p);
	}
	marker_ruta__.setAnimation(google.maps.Animation.BOUNCE);
	// colocar la ventana de informacion para la ruta
	show_msj_ruta();
}
function show_msj_ruta(){
	var clr = '<div class="limpiar" style="height:10px;"></div>';
	var html = clr 
	html += '<div class="v-cnt-box contar">';
	html += '	<div class="btn-cerrar" onClick="restart_all()"><img src="img/uc2-close.png" border="0" /></div>';
	html += '	<div class="limpiar" style="height:1px;"></div>';
	html += '	<p id="title_casillas" class="v-box-title">Ruta a Casilla</p>';
	html += '</div>' + clr;
	html += '<div class="v-cnt-box">';
	html += '	<label><input type="radio" checked="checked" value="0" name="opc_ruta" id="r_opc_0">En automóvil</label>';
	html += '	<label><input type="radio" value="1" name="opc_ruta" id="r_opc_1">A pie</label>';
	html += '</div>' + clr;
	html += '<div class="v-cnt-box">';
	html += '	<p class="mv-texto" style="text-align:center; font-size:0.7em;"><i>Arrastra la <b>figura</b> para cambiar tu posición</i></p>';
	html += '</div>' + clr;
	html += '<div class="v-cnt-box">';
	html += '	<div style="display:block; margin:auto; width:auto; text-align:center;">';
	html += '		<p onclick="calcular_ruta()" class="button button-orange">¿Como llegar?</p>';
	html += '	</div>';
	html += '</div>' + clr;
	$('#mvoladorcfg').html(html);
	$('#mvoladorcfg').fadeIn('fast')
	msj_ruta_visible__ = true;
}
function restart_all(){
	mvolador_hide();
	mvoladorcfg_hide();
	limpiar_markers();
	clear_infowindow();
	var toggle = panorama__.getVisible();
	if (toggle == true) {
      panorama__.setVisible(false);
    }
	bandera_ruta__ = false;
	msj_ruta_visible__ = false;
	if(marker_ruta__){
		marker_ruta__.setMap(null);
		marker_ruta__ = null;
	}
	id_marker_ruta__ = -1;
	directionsDisplay.setMap(null);
	$('#rutas').stop().animate({'marginLeft':'-2px'},200);
	$('#box_response_ruta').empty();
}
function change_marker(n){
	limpiar_markers();
	list_objets__[n].setIcon('/img/uc2-casilla-on.png');
}
function select_marker(i){
	var point = list_objets__[i].getPosition();
	//alert('i: '+i.toString()+' | getpos: '+ list_objets__[i].getPosition() +' | pos: ' + point.toString());
	set_center(point,15);
	//alert('despues de centrar');
	bandera_ruta__ = false;
	restart_all();
	//alert('restaura todo');
	change_marker(i);
	//alert('cambia marker');
}
function put_valores(txt){
	var valores = eval('(' + txt + ')');
	$('#box_response').empty();
	restart_all();
	clear_map();
	if(valores.mensage == '1'){
		var html = '<p class="v-box-title">Sin Casillas</p><div class="limpiar" style="height:2px;"></div>';
		$('<div class="v-cnt-box">').html(html).prependTo('#box_response');
		mvolador_show('uc2-alert.png','No se encontraron resultados. Intente con otra opción',4000,false);
	}else{
		var mun = '';
		var mun_tmp = '';
		var n = valores.valores.length;
		for (var i = 0; i < n; i++){
			var entidad_ = valores.valores[i].entidad.toString();
			var distrito_ = valores.valores[i].distrito.toString();
			var mun_num_ = valores.valores[i].municipio_num.toString();
			var mun_nom_ = clear_str(valores.valores[i].municipio_nom.toString());
			mun = mun_nom_;
			var seccion_ = valores.valores[i].seccion.toString();
			var casilla_ = valores.valores[i].casilla.toString();
			var domicilio_ = clear_str(valores.valores[i].domicilio.toString());
			var ubicacion_ = clear_str(valores.valores[i].ubicacion.toString());
			var referencia_ = clear_str(valores.valores[i].referencia.toString());
			var letra_ini_ = clear_str(valores.valores[i].letra_ini.toString());
			var letra_fin_ = clear_str(valores.valores[i].letra_fin.toString());
			var coordenadas_ = remplaza('&',',',valores.valores[i].coordenadas.toString());
			var key_ss_ = valores.valores[i].key_ss.toString();
			if(mun != mun_tmp){
				put_municipio(mun);
				mun_tmp = mun;
			}
			if(coordenadas_ != '' && coordenadas_ != 'None' && coordenadas_ != undefined){
				put_descripcion(domicilio_,coordenadas_,key_ss_,i);
				var auxc = put_style_valor(i,key_ss_,seccion_,casilla_,letra_ini_,letra_fin_,coordenadas_);
				var auxd = put_style_text(domicilio_);
				var auxu = put_style_text(ubicacion_);
				var auxr = put_style_text(referencia_);
				put_m_casilla(i,key_ss_,coordenadas_,auxc,auxd,auxu,auxr);
			}else{
				var info = 'En esta sección se encuentra(n) la(s)  casilla(s) -<b>'+ casilla_+'</b>-, pero no se tiene definida su ubicación aun.<br />Ponte en contacto con nosotros para mas información.';
				mvolador_show('pel-alert.png','<b>ALERTA</b><br />'+ info,7000,false);
			}
		}
		var html = '<p class="v-box-title">Lista de Casillas</p><div class="limpiar" style="height:2px;"></div>';
		$('<div class="v-cnt-box">').html(html).prependTo('#box_response');
		put_ss_tooltip(); // Coloca los tooltip a todas las casillas
		map__.fitBounds(bounds__);
		map__.setZoom(map__.getZoom() - 5);
	}
}
function put_m_casilla(i,key_ss,v1,v2,v3,v4,v5){
	var name = i.toString();
	var image = '/img/uc2-casilla-off.png';
	var shadow = '/img/uc2-shadow-casilla.png';
	var punto = get_point_coordenadas(v1);
	var marker = new google.maps.Marker({
	    position: punto,
	    map: map__,
		icon: image,
		shadow: shadow,
		draggable: false,
		animation: google.maps.Animation.DROP,
		title:'Casilla'
	});
	var espacio = '<div class="limpiar" style="height:1px;"></div>';
	var str_html = '<p class="map_text" style="font-weight:bold;">Casilla</p>' + espacio;
	str_html += v2 + espacio;
	str_html += '<p class="map_text" style="font-weight:bold;">Domicilio</p>' + espacio;
	str_html += v3 + espacio;
	str_html += '<p class="map_text" style="font-weight:bold;">Ubicación</p>' + espacio;
	str_html += v4 + espacio;
	str_html += '<p class="map_text" style="font-weight:bold;">Referencia</p>' + espacio;
	str_html += v5 + espacio + '<div class="limpiar" style="height:16px;"></div>';
	var infowindow_ = new google.maps.InfoWindow({
		content: str_html
	});
	marker.infowindow = infowindow_;
	google.maps.event.addListener(marker, 'click', function() {
		clear_infowindow();
		marker.infowindow.open(map__,marker);
		var name_revisar = 'boxstreet__'+name;
		check_sv(v1,name_revisar);
	});
	list_objets__.push(marker);
	bounds__.extend(punto);
	efect_list();
}

function efect_list(){
	$('#casillas').stop().animate({'marginLeft':'-2px'},200);
}

function calcular_ruta(){
	msj_ruta_visible__ = false;
	if(marker_ruta__){
		var pinicial = marker_ruta__.getPosition();
		var final = list_objets__[id_marker_ruta__].getPosition();
		opc_ruta__ = google.maps.DirectionsTravelMode.DRIVING;
		if(document.getElementById('r_opc_1')){
			if(document.getElementById('r_opc_1').checked){
				opc_ruta__ = google.maps.DirectionsTravelMode.WALKING;
			}
		}
		var request = {
			origin: pinicial,
			destination: final,
			travelMode: opc_ruta__
		};
		mvoladorcfg_hide();
		mvolador_show('uc2-loader.gif','<b>Calculando Ruta</b>, Espere Por Favor...',0,true);
		//Calculamos la ruta
		directionsService.route(request, function(response, status) {
				$('#box_response_ruta').empty();
				mvolador_hide();
				if (status == google.maps.DirectionsStatus.OK) {
					directionsDisplay.setMap(map__);
					directionsDisplay.setDirections(response);
					bandera_ruta__ = true;
				}else{
					//Muestra mensaje de no encontro rutas y kita mapita
					if(!bandera_ruta__){
						bandera_ruta__ = false;
					}
					mvolador_show('uc2-error.png','<b>Error...</b><br />'+ status,4000,false);
				}
		});
	}else{
		mvolador_show('uc2-error.png','<b>Error...-No se puede calcular la ruta-</b><br />No se encontraron datos de tu ubicación',4000,false);
	}
}
function put_message_hover(html,referencia){
	$(referencia).hover(
		function () {
			if(!msj_ruta_visible__){
				$('#mvoladorcfg').html(html);
				$('#mvoladorcfg').fadeIn('fast')
			}
		},
		function () {
			if(!msj_ruta_visible__){
				mvoladorcfg_hide();
			}
		}
	);
}
function get_parametro(variable){
	var direccion = location.href;
	var posicion = direccion.indexOf("?");
	posicion = direccion.indexOf(variable,posicion) + variable.length;
	if (direccion.charAt(posicion) == "="){
		var final = direccion.indexOf("&",posicion);
		if (final == -1){
			final=direccion.length;
		}
		return decode_url(direccion.substring(posicion + 1,final));
	}
}
function decode_url(txt){
	var str = txt.replace('%*','%');
	str = unescape(str);
	return str;
}
