function carga_galeria() {
		visores = $$('.visor_fotos');
		
		for (i=0; i< visores.length; i++) {
			// Poner el offset a 0 al refrescar
			lst = visores[i].readAttribute("id").split("_");
			ga_id = lst[1];
			$("offsetActual_" + ga_id).value = 0;
			
			elemPrev = visores[i].getElementsByClassName('goPrev');
			elemNext = visores[i].getElementsByClassName('goNext');
			
			if (visores[i].hasClassName('coleccion') == true) {
				if (elemPrev != null) {
					Event.observe(elemPrev[0], "click", goPrevColeccion);
				}
				if (elemNext != null) {
					Event.observe(elemNext[0], "click", goNextColeccion);
				}
			}
			else {
				if (elemPrev != null) {
					Event.observe(elemPrev[0], "click", goPrev);
				}
				if (elemNext != null) {
					Event.observe(elemNext[0], "click", goNext);
				}
			}
			
		}
    }


Event.observe(window, 'load', carga_galeria);
    
/*
 * FUNCIONES MOVER GALERIAS
 */
function goPrev(evento) {
	
	var contexto = $('contexto').firstChild.nodeValue;
	
	el_controlador = Event.element(evento);
	lst = el_controlador.readAttribute("id").split("_");
	
	id = lst[2];
	offset = $("offsetActual_" + id).value;
	offset = parseInt(offset) - 1;
	
	if (offset == 0) {
		$('img_goPrev_' + id).src = 'http://www.alpeteam.com/estilos/' + contexto + '/flecha_atras_nor.gif'; 
		$('img_goPrev_' + id).addClassName('noClick');
	}
	
	if ($('img_goNext_' + id).hasClassName('noClick'))
	{
		$('img_goNext_' + id).src = 'http://www.alpeteam.com/estilos/' + contexto + '/flecha_adelante_act.gif'; 
		$('img_goNext_' + id).removeClassName('noClick');
	}
  
	if (offset >= 0) {		
		$("offsetActual_" + id).value = offset;
		moverTira(id, offset, false);
	}
	return false;
}

function goNext(evento) {
		
	var contexto = $('contexto').firstChild.nodeValue;
		
	el_controlador = Event.element(evento);
	lst = el_controlador.readAttribute("id").split("_");
	
	id = lst[2];
	
	offset = $("offsetActual_" + id).value;
	offset = parseInt(offset) + 1;
	offsetMaximo = $("offsetMax_" + id).value;
	
	if (offsetMaximo <= 0)
		return false;
    
	if ($('img_goPrev_' + id).hasClassName('noClick'))
	{
		$('img_goPrev_' + id).src = 'http://www.alpeteam.com/estilos/' + contexto + '/flecha_atras_act.gif'; 
		$('img_goPrev_' + id).removeClassName('noClick');
	}
  
	if (offset == offsetMaximo) {
		$('img_goNext_' + id).src = 'http://www.alpeteam.com/estilos/' + contexto + '/flecha_adelante_nor.gif';  
		$('img_goNext_' + id).addClassName('noClick');
	}
  
	if (offset <= offsetMaximo) {
		$("offsetActual_" + id).value = offset;
		moverTira(id, offset, true);
	}
  
	return false;
	
}


function moverTira(ga_id, offset, avance) {
    ajaxurl = "/ajax_galeria";
    
    if ($("modelos_" + ga_id) != null) {
    	modelos = $("modelos_" + ga_id).value;
    }else {
    	modelos = false;
    }
    
    new Ajax.Request(ajaxurl, {
        method:'get', 
        encoding:'UTF-8',
        asyncronous: false,
        evalJSON: true,
        parameters: {id_galeria: ga_id,
                     offset: offset,
                     resultados: ""},
        onCreate: function(){
          
          pos = "1";
          if (avance == true) { pos = "4"; }
          
          elem = $('foto_' + ga_id + "_" + pos);
          elem.src = 'http://www.alpeteam.com/estilos/alpeteam/loader_grande.gif';
          
        },
        onFailure:function(){
          alert('Fallo carga fotos');
        },
        onComplete: function(transport, json){
          
          lst_fotos = json.lst_fotos;
          
          for (i=0; i<lst_fotos.length; i++)
          {
            id = lst_fotos[i][0]
            id_foto = lst_fotos[i][1]
            modelo = lst_fotos[i][2]
            ruta_thum = lst_fotos[i][3];
            ruta_foto = lst_fotos[i][4];            
            
            elem = $('foto_' + ga_id + "_" + (i+1));
            elem.src = "http://www.alpeteam.com/images/" + ruta_thum;
            
            elemOcul = $('full_' + ga_id + "_" + (i+1));            
            elemOcul.value = ruta_foto;
            
            numelem = $('num_foto_' + ga_id + "_" + (i+1));  
            numFoto = i + 1 + offset;
            
            // Actualizamos el numero o el modelo
            if (modelos == 'true') { numelem.update("<b>" + modelo + "</b>"); }
            else { numelem.update("<b>" + numFoto + "</b>"); }
            
            valor = i + 1;
          }         
          
        }
    });
}


/*
 * FUNCIONES MOVER COLECCIONES
 */
 function goPrevColeccion(evento) {
		
	var contexto = $('contexto').firstChild.nodeValue;
	
	el_controlador = Event.element(evento);
	lst = el_controlador.readAttribute("id").split("_");
	
	id = lst[2];
	offset = $("offsetActual_" + id).value;
	offset = parseInt(offset) - 12;
	
	if (offset == 0) {
		$('img_goPrev_' + id).src = 'http://www.alpeteam.com/estilos/' + contexto + '/flecha_arriba_nor.gif'; 
		$('img_goPrev_' + id).addClassName('noClick');
	}
	
	if ($('img_goNext_' + id).hasClassName('noClick'))
	{
		$('img_goNext_' + id).src = 'http://www.alpeteam.com/estilos/' + contexto + '/flecha_abajo_act.gif'; 
		$('img_goNext_' + id).removeClassName('noClick');
	}
  
	if (offset >= 0) {
		$("offsetActual_" + id).value = offset;
		moverColeccion(id, offset);
	}
	
	return false;
}

function goNextColeccion(evento) {
	
	var contexto = $('contexto').firstChild.nodeValue;
		
	el_controlador = Event.element(evento);
	lst = el_controlador.readAttribute("id").split("_");
	
	id = lst[2];
	
	offset = $("offsetActual_" + id).value;
	offset = parseInt(offset) + 12;
	offsetMaximo = $("offsetMax_" + id).value;
	
	
	if (offsetMaximo <= 0)
		return false;

	if ($('img_goPrev_' + id).hasClassName('noClick'))
	{
		$('img_goPrev_' + id).src = 'http://www.alpeteam.com/estilos/' + contexto + '/flecha_arriba_act.gif'; 
		$('img_goPrev_' + id).removeClassName('noClick');
	}
  
	if (offset == offsetMaximo) {
		$('img_goNext_' + id).src = 'http://www.alpeteam.com/estilos/' + contexto + '/flecha_abajo_nor.gif';  
		$('img_goNext_' + id).addClassName('noClick');
	}
  
	if (offset <= offsetMaximo) {
		$("offsetActual_" + id).value = offset;
		moverColeccion(id, offset);
	}
  
	return false;
	
}


function moverColeccion(ga_id, offset) {
	
	carrito = false;
	
	path_ficheros = 'http://www.alpeteam.com/images/';
	ajaxurl = "/ajax_galeria";
	dict_params = {
		id_galeria: ga_id,
        offset: offset,
        resultados: 12 }
	
	// Actualizar galeria de modelos actuales
	if ($("temporada_modelos_actuales")) { 
		path_ficheros = '/images/';
		dict_params = {
			temporada : $("temporada_modelos_actuales").value,
			filtro: $("filtro").value,
			offset: offset,
			json: true
		}
		
		tipo_usuario = $F($('tipo_usuario'));
		dict_urls = {
				 'cliente' : '/cliente/modelos/actuales/actualiza/',
				 'agente' : '/agente/modelos/actuales/actualiza/'
		};
				
		ajaxurl = dict_urls[tipo_usuario];
		if (!ajaxurl) {
			return false;
		}else {
			carrito = true;	
		}
	}
	
	// Actualizar galeria de modelos de liquidacion
	if ($("temporada_modelos_liquidacion")) {
		path_ficheros = '/images/';
		dict_params = {
			temporada : $("temporada_modelos_liquidacion").value,
			offset: offset,
			json: true
		}
		
		tipo_usuario = $F($('tipo_usuario'));
		dict_urls = {
				 'cliente' : '/cliente/modelos/liquidaciones/actualiza/',
				 'agente' : '/agente/modelos/liquidaciones/actualiza/'
		};
				
		ajaxurl = dict_urls[tipo_usuario];
		if (!ajaxurl) {
			return false;
		}else {
			carrito = true;	
		}
		
	}
	
	
    if ($("modelos_" + ga_id) != null) {
    	modelos = $("modelos_" + ga_id).value;
    }else {
    	modelos = false;
    }
    
    new Ajax.Request(ajaxurl, {
        method:'post', 
        encoding:'UTF-8',
        evalJSON: true,
        parameters: dict_params,
        onCreate: function(){
          
          for (var pos=1; pos<=12; pos++) {
	          elem = $('foto_' + ga_id + "_" + pos);
	          
	          if (elem.hasClassName('oculto') == true) {
	        	  elem.removeClassName('oculto');
	          }
	          elem.src = 'http://www.alpeteam.com/estilos/alpeteam/loader_grande.gif';
	          
	          elem = $('num_foto_' + ga_id + "_" + pos);
	          elem.update('');
          }
          
        },
        onFailure:function(){
          alert('Fallo carga fotos');
        },
        onComplete: function(transport, json){
        	
          lst_fotos = json.lst_fotos;
          
          for (i=0; i<lst_fotos.length; i++)
          {
            id = lst_fotos[i][0]
            id_foto = lst_fotos[i][1]
            modelo = lst_fotos[i][2]
            ruta_thum = lst_fotos[i][3];
            ruta_foto = lst_fotos[i][4];
            
            if (ruta_thum == false) {
	            elem = $('foto_' + ga_id + "_" + (i+1));
	            elem.src = '/img/sin_foto.png';
	            
	            if (elem.hasClassName('fotoThumbnail')) { elem.removeClassName('fotoThumbnail');}
	            elem.stopObserving('click');
	            
	            elemOcul = $('full_' + ga_id + "_" + (i+1));            
	            elem.src = '/img/sin_foto.png';
            }
            
            else {
	            elem = $('foto_' + ga_id + "_" + (i+1));
	            elem.src = path_ficheros + ruta_thum;
	            if (!elem.hasClassName('fotoThumbnail')) { elem.addClassName('fotoThumbnail');}
	            
	            elemOcul = $('full_' + ga_id + "_" + (i+1));            
	            elemOcul.value = ruta_foto;
            }
            
            numelem = $('num_foto_' + ga_id + "_" + (i+1));  
            numFoto = i + 1 + offset;
            
            // Actualizamos el numero o el modelo
            if ((modelos == 'true') || (modelos == true)) {             	
            	if (carrito == true){
            		
            		img_carrito = "<img src='/img/carrito_vacio.gif' alt='' />";
            		if (lst_fotos[i][5] == true) {
            			img_carrito = "<img src='/img/carrito.gif' alt='' />";
            		}
                  		            		
            		txt_html = "<span class='numero_modelo'>";
            		txt_html += "<b>" + modelo + "</b></span> ";
            		txt_html += "<span class='carrito'>";
            		txt_html += "<a href='#' id='m_" + modelo + "' class='modeloCarrito'>";
            		txt_html += img_carrito + "</a></span>";
            	}
            	else {
            		txt_html = "<b>" + modelo + "</b>";
            	}
            	
            	numelem.update(txt_html); 
            }
            else {
            	numelem.update("<b>" + numFoto + "</b>"); 
            }
            
          }
          
          if (lst_fotos.length) {
        	  for (x=lst_fotos.length; x<12; x++) {
        		  numelem = $('num_foto_' + ga_id + "_" + (x+1)); 
        		  numelem.update("<b></b>");              
	              elem = $('foto_' + ga_id + "_" + (x+1));
	              elem.addClassName('oculto');
        	  }
        	  
          }
          
          // Llamamos al visor
          initViewer();
          
          // Llamamos a generar eventos de modelos
          if (carrito == true) {
          	evt_modelos();
          }

        }
    });
}


function cambia_pais_comerciales(id_region, contexto) {
    ajaxurl = "/ajax_alpe_mundo";
    
    new Ajax.Request(ajaxurl, {
        method:'get', 
        encoding:'UTF-8',
        evalJSON: true,
        parameters: {id_region: id_region,
    				contexto: contexto},
        onLoading: function(){
          
        },
        onFailure:function(){
          alert('Fallo carga datos');
        },
        onSuccess: function(transport, json){        	
        	$('datos_comerciales').update(transport.responseText);
        }
    });
}


function cambia_region_comerciales(id_region, contexto) {
    ajaxurl = "/ajax_red_agentes";
    
    lst_ids = {
    	"13": "gl",
    	"24": "cl",
    	"9": "md",
    	"25": "ex",
    	"20": "an",
    	"23": "cm",
    	"12": "mu",
    	"10": "va",
    	"26": "ca",
    	"15": "ar",
    	"18": "na",
    	"17": "ri",
    	"19": "pv",
    	"16": "cn",
    	"14": "as",
    	"27": "cs",
    	"11": "ba"
    }
    
    lst_keys = Object.keys(lst_ids).sort();
    
    for (i=0; i<lst_keys.length; i++) {
    	elemA = $(lst_ids[lst_keys[i]]).getElementsBySelector("a")[0];
    	elemA.removeClassName('selected');
    }
    
    elemA = $(lst_ids[id_region]).getElementsBySelector("a")[0]
    elemA.addClassName("selected");
    
    new Ajax.Request(ajaxurl, {
        method:'get', 
        encoding:'UTF-8',
        evalJSON: true,
        parameters: {id_region: id_region,
					 contexto: contexto},
        onLoading: function(){
          
        },
        onFailure:function(){
          alert('Fallo carga datos');
        },
        onSuccess: function(transport, json){        	
        	$('datos_comerciales').update(transport.responseText);
        }
    });
}
