function showMessage(_text, _class) {
  	$("#message").removeClass('hidden');
    $("#message").addClass(_class);
	$("#message p").replaceWith(_text);
	$('#message').fadeIn('slow').animate({opacity: 1.0}, 5000).fadeOut('slow');		
}


function createMarker(point, map) {
	var marker = new GMarker(point);
	GEvent.addListener(marker, "click", function() {
		var myHtml = "Partida Cabiscol, s/n.<br />Apartat de correus, 238<br />43870 Amposta ( TARRAGONA )";
		map.openInfoWindowHtml(point, myHtml);
	});

	return marker;
}

// Function that return a number between 0 and "nums - 1"
function getRandom(nums) {
	var ranNum= Math.round(Math.random()*nums);
	return ranNum;
}

// Method for queal column into group like id or class
function equalHeight(group) {
	var tallest = 0;
	group.each(function() {
		var thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
}

function limitLines(ref, max) {
	
	var ref = $(ref);
    var arr = ref.text().split('\n');
    window.alert(ref.text());
    /*
    for (var i = 0; i < arr.length; i++) {
        $(ref).after(i + '=' + arr[i] + '<br/>');
    }
    */
}

function getHost() {
	var url = window.location.toString();
	//var urlparts = url.split('/');
	//var host = urlparts[0];
	return url;
}

function getProductCategory() {
	var url = getHost();
	var urlparts = url.split('/');
	var category = urlparts[urlparts.length-1];
	alert(category);
	return category;
}

/********** Funciones dependientes de JQUERY y estado del documento */
$().ready(function(){

    // Open new windows avoiding target='_blank' and using rel="external"
    fix_external_links();
    
    // Fix transparency
    $(document).pngFix(); 
    
    var baseScript = $('base').attr('href');
	
    // Header flash
    
    if ($('#banner').length > 0) {
    	
    	if ($('#home').length > 0) sceneID = 1;
    	else if ($('#contact').length > 0) sceneID = 5;
    	else if ($('#newspaper').length > 0) sceneID = 3;
    	else if ($('#distributors').length > 0) sceneID = 4;
    	else if ($('#company').length > 0) sceneID = 2;
		else sceneID = 1;
    	
	
		if ($('#flashLaunch').length > 0) {	
			path = 'public/swf/products_' + language + '.swf';			
			value = $('#flashLaunch').attr('name');
			vars = { firstScene: value};
		} else {
			path = 'public/swf/header_' + language + '.swf';	
			vars = { firstScene: sceneID };
		}
		
		$('#banner').flash(
		{
			src: path,
			width: 945,
			height: 350,
			wmode: 'transparent',
			flashvars: vars
		},
		{ version: 10 }
		);		
	
	}

    // Validador del formulario
/*    if ($('#formContact').length > 0) {
        var validation = $('#formContact').validate({           
            errorElement: 'em',
            /*debug: true,
            invalidHandler: function(){
                showMessage('Se han detectado errores en el formulario. Por favor, revise los datos enviados', 'warning')
            },
            */
/*			submitHandler: function(form) {
			   	form.submit();
			  }
			
        });
        
    }    */
    
    // Altura del cuerpo de la web
    if ($('#main').length > 0 && $('#home').length == 0 && $('#products').length == 0 && $('#gruas').length == 0) {
    	
    	if ($('#main').height() < 900) {
    		$('#main').height(900);	
		}
    	
    }
    
    // Fix equal columns for news
    if ($('#main-news').length > 0) {    	
    	equalHeight($("#main-news"));    	
    }   
    
    // Fix equal columns for news
    if ($('#productsList').length > 0) {    	
    	equalHeight($("#productsList li"));    	
    }       
		
    // Inicializador de mapa Google
	if ($('#google_maps').length > 0) {
		
		var mark;
		var pointA;
		var pointB;
		var debug = 0;
		
		if (GBrowserIsCompatible()) {
		
			var m = $("#google_maps")[0];
			if (m) {
			
				// Datos del mapa
				var map = new GMap2(m);
				var start = new GLatLng(21.289374355860424, 12.65625);
				var zoomLevel = 1;	
				var locations = new Array();
				
				// Inicializamos mapa con datos anteriores
				map.setMapType(G_PHYSICAL_MAP);				
				map.removeMapType(G_HYBRID_MAP);
				map.addMapType(G_PHYSICAL_MAP);
				// Set new controls
				var mapControl = new GMapTypeControl();								
				map.addControl(mapControl);
				map.addControl(new GLargeMapControl());
				map.addControl(new GMapTypeControl());	
				map.setCenter(start, zoomLevel);				
				
				// Evento para activar/desactivar marcas del mapa
				GEvent.addListener(map,'click',function(overlay, point) {
					
					if (mark) {	map.removeOverlay(mark); }
					if (point) {
						map.getCenter(point);
						$('#lng').attr('value',point.x);
						$('#lat').attr('value',point.y);	
						if (debug == true) {
							$('#coords').text("'lat' => " + point.x + ", 'lng' => " + point.y + ", 'zoom' => " + map.getZoom().toString());
						}
					}	
				});
				
			 	// Debugger
				if (debug == 1) {
					GEvent.addListener(map, "moveend", function() {
						var center = map.getCenter();
						var zoom = map.getZoom();	
						if (debug == true) {
							$('#coords').text("'lat' => " + center.toString() + ", 'zoom' => " + zoom.toString());
						}
					});
				}
				

			    function createMarker(stores) {
					var store = stores[0];
					var newIcon = MapIconMaker.createMarkerIcon({width: 32, height: 32, primaryColor: store.type});
					var marker = new GMarker(store.latlng, {icon: newIcon});
					var html = '<h1 style="font-size: 12px">' + store.name + '</h1><p style="font-size: 11px">' + store.address + '</p>';
					GEvent.addListener(marker, 'click', function() {
						marker.openInfoWindowHtml(html);
					});
					map.addOverlay(marker);
			    }
				
				function createClusteredMarker(stores) {
					for (var i = 0; i < stores.length; i++) {
						var store = stores[i];
						var html = '<h1 style="font-size: 12px">' + store.name + '</h1><p style="font-size: 11px">' + store.address + '</p>';
						var newIcon = MapIconMaker.createMarkerIcon({width: 32, height: 32, primaryColor: store.type});
						var marker = new GMarker(store.latlng, {icon: newIcon});
						GEvent.addListener(marker, 'click', function() {
							marker.openInfoWindowHtml(html);
						});

						map.addOverlay(marker);
					}
				}

				function iconType(type) {

					var _type = '';

					switch (type) {
						case 'colab':
							_type = '#ff9900';
						break;
						default:
							_type = '#336699';
						break;
					}

					return _type;

				}
				
				
				// Script de carga de informacion GEOLocalizacion
				GDownloadUrl(baseScript + "/public/javascripts/distribuidoresCayvol.xml", function(data, responseCode) {
					
					if(responseCode == 200) {						
						var xml = GXml.parse(data);
						var markers = xml.documentElement.getElementsByTagName("marker");
						// Recorre array de marcadores
						for (var i = 0; i < markers.length; i++) {
							var name = markers[i].getAttribute("name");
							var address = markers[i].getAttribute("address");
							var address = (address.split('|')).join('<br>');
							var type = iconType(markers[i].getAttribute("type"));
							var latlng = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
							var store = {latlng: latlng, name: name, address: address, type: type};
							var latlngHash = (latlng.lat().toFixed(6) + "" + latlng.lng().toFixed(6));
							latlngHash = latlngHash.replace(".","").replace(".", "").replace("-","");
							if (locations[latlngHash] == null) {
								locations[latlngHash] = [];
							}
							
							locations[latlngHash].push(store);
						
						}			
						
						ubicarMarcas();
					
					} else if(responseCode == -1) {
					    alert("Data request timed out. Please try later.");
					  } else { 
					    alert("Request resulted in error. Check XML file is retrievable.");
					  }

				});		
				
				// Function ubicar marcas
				function ubicarMarcas() {
					// Ubica marcadores
					for (var latlngHash in locations) {		
						var stores = locations[latlngHash];
						if (stores.length > 1) {
							createClusteredMarker(stores);
						} else {
							createMarker(stores);
						}
					}
				}
				

				$('#provincia').change(function() {
					
					
					if ($(this).val() != 0) {
						
						var district = 'district=' + $(this).val();

						$.ajax({
							
							type: 'POST',
							data: district,
							url: 'distributors/info/',
							success: function(r) {
								var coord = r.split("|");
								pointB = new GLatLng(coord[1],coord[2]);
								map.setCenter(pointB,parseInt(coord[3]));
								$('#lat').attr('value',coord[1]);
								$('#lng').attr('value',coord[2]);
								$('#pais_title').text(coord[0]);
								ubicarMarcas();
	
							}
							
						});
					
					}
				
				
				});		
				
			}
			
		}		
		
	}
	    
});


