var ILat 	= 48.69096;
var ILng 	= -32.34375;
var IZoom 	= 2;
var DLat 	= 37.8575;
var DLng 	= -100.54687;
var DZoom 	= 3;
var Markers		= new Array();
var mapPoint 	= new Array();
var to_country_id 	= 0;
var map;
var map_type 	= 0;
var directions;
var is_show;

function Initialize() 
{
    if (GBrowserIsCompatible()) 
	{
		map = new GMap2($('map_direction'), {size: new GSize(530,400)});
		map.enableScrollWheelZoom();
		map.addControl(new GLargeMapControl());
		map.addControl(new GScaleControl());
		map.addControl(new GMapTypeControl());
	}
}
function LoadMap(map_type, is_show)
{
    if ( !map ) {
        return;
	}
	map.clearOverlays();
	ShowMap(map_type, is_show);
}
function ShowMap(map_type, is_show) 
{
    if ( !map ) {
        return;
	}

	if(is_show == 1 && map_type >= 0) {
		ClearMarkers(map_type);
	}
	
	if(map_type == 1)
	{
		query = 'country';
		input = 'to_country';
		all_label = msg['country'];
	} else if(map_type == 2) {
		query = 'port/'+to_country_id;
		input = 'to_port';
		all_label = msg['port'];
	} else if (map_type == 3) {
		query = 'usaport/'+to_port_id;
		input  = 'usa_port';
		all_label = msg['port_usa'];
	} else if (map_type == 4) {
		query = 'border-crossing';
		input = 'to_border_crossing';
		all_label = msg['border_crossing'];
	} else if (map_type === 0) {
		query = 'facility';
		input = 'from_yard';
		all_label = msg['facility'];
	} else {
		ShowMarkers(0);
		return;
	}

	new Ajax.Request(url+"shipping-salvage-vehicles/"+query+"/"+$('h').value+"/", {
        method: "get",
        evalJSON: true,
    	onSuccess: function(transport){
			Doc = transport.responseJSON.markers;
			
			DocCounter = Doc.length;
			if(DocCounter > 0) 
			{
				mapPoint[map_type] 	= new Array();
				Markers[map_type] 	= new Array();
	
				if(is_show == 1) {
					$(input).options.length = 0;
					$(input).options[0] = new Option(all_label, '');
				}
				for ( var i = 0; i < DocCounter; i++ )
				{
					if(Doc[i] !== null && Doc[i])
					{
						mapPoint[map_type][i] 			= new Array(); 
						mapPoint[map_type][i]["lat"] 	= parseFloat(Doc[i].lat);
						mapPoint[map_type][i]["lng"] 	= parseFloat(Doc[i].lng);
						mapPoint[map_type][i]["id"] 	= parseInt(Doc[i].id, 10);
						mapPoint[map_type][i]["name"] 	= Doc[i].name;
						mapPoint[map_type][i]["pnt"] 	= new GLatLng( mapPoint[map_type][i]["lat"], mapPoint[map_type][i]["lng"]);
		
						Markers[map_type][i] 			= new Object();
						Markers[map_type][i].marker 	= CreateMarker(mapPoint[map_type][i]["id"], mapPoint[map_type][i]["pnt"], mapPoint[map_type][i]["name"], map_type);
						Markers[map_type][i].marker.hide();
						Markers[map_type][i].id 		= mapPoint[map_type][i]["id"];
						Markers[map_type][i].name 		= mapPoint[map_type][i]["name"];
						
						if(is_show == 1) {
							$(input).options[i + 1] = new Option(mapPoint[map_type][i]["name"], mapPoint[map_type][i]["id"]);
						}
						map.addOverlay(Markers[map_type][i].marker);
					}
				}
				if(is_show == 1) {
					ShowMarkers(map_type);
				}
			} 
            else {
            	alert("Data request timed out.\nPlease try again later.");
            }
        },
        onFailure: function(){
            alert("Data request timed out.\nPlease try again later.");
        }
    });
}
function CreateMarker(id, point, name, map_type) 
{
	markerIcon = new GIcon();
	markerIcon.shadow = "/i/icons/marker_shadow.png";
	markerIcon.iconSize = new GSize(32, 32);
	markerIcon.shadowSize = new GSize(59, 32);
	markerIcon.iconAnchor = new GPoint(15, 32);

	if (map_type == 1) {
		markerIcon.image = "/i/icons/marker_red.png";
	} else if (map_type == 2) {
		markerIcon.image = "/i/icons/marker_blue.png";
	} else if (map_type == 3 || map_type == 4) {
		markerIcon.image = "/i/icons/marker_green.png";
	} else if (map_type === 0) {
		markerIcon.image = "/i/icons/marker_yellow.png";
	}
	
	markerOptions = { icon: markerIcon, title: name };
    var marker = new GMarker(point, markerOptions);

	if (map_type == 1) {
        GEvent.addListener(marker, "click", function() {
			markerCountryClick(id);
        });
	} else if (map_type == 2) {
        GEvent.addListener(marker, "click", function() {
			markerPortClick(id);
        });
	} else if (map_type == 3) {
        GEvent.addListener(marker, "click", function() {
			markerUsaPortClick(id);
        });
	} else if (map_type == 4) {
        GEvent.addListener(marker, "click", function() {
			markerBorderCrossingClick(id);
        });
	} else if (map_type === 0) {
        GEvent.addListener(marker, "click", function() {
			markerYardClick(id);
        });
	}
    return marker;
}
function ShowMarkers(map_type) 
{
	var dohide = 0;
	var doshow = 0;
	for (var t = 0; t < 5; t++) 
	{
		if(Markers[t] !== null && Markers[t] !== undefined && Markers[t])
		{
			if(Markers[t].length > 0)
			{
				for (var m = 0; m < Markers[t].length; m++) 
				{
					if(Markers[t][m] !== null && Markers[t][m] !== undefined &&  Markers[t][m])
					{
						if (t === map_type) {
							Markers[t][m].marker.show();
							doshow = 1;
						} else {
							Markers[t][m].marker.hide();
							dohide = 1;
						}
					}
				}
			}
		}
	}
	if(doshow) {
		zoomMap(map_type);
	}
}
function ClearMarkers(map_type) 
{
	if(Markers[map_type] !== null && Markers[map_type])
	{
		for (var m = 0; m < Markers[map_type].length; m++) 
		{
			if(Markers[map_type][m] !== null && Markers[map_type][m])
			{
				map.removeOverlay(Markers[map_type][m].marker);
			}
		}
		Markers[map_type] = null;
	}
}

function HideMarkers(map_type) 
{
	if(Markers[map_type] !== null && Markers[map_type])
	{
		for (var m = 0; m < Markers[map_type].length; m++) 
		{
			Markers[map_type][m].marker.hide();
		}
	}
}

function zoomMap( map_type ) 
{
	var bounds = new GLatLngBounds();
	if(Markers[map_type] !== null && Markers[map_type])
	{
		for (var i=0; i< Markers[map_type].length; i++) 
		{
			bounds.extend(Markers[map_type][i].marker.getLatLng());
		}
		if (Markers[map_type].length > 1) 
		{
			var zoom = map.getBoundsZoomLevel(bounds);
			if (Markers[map_type].length == 2 && zoom > 1) 
			{
				zoom--;
			}
			map.setZoom(zoom);
		} else {
			map.setZoom(10);
		}
	} else {
		map.setZoom(10);
	}

	map.setCenter(bounds.getCenter());
}

function markerCountryClick(id) 
{
	hide_results();
	$('to_country').value  = id;
	to_country_id = id;
	$('table-usa_port').style.display = 'none';
	$('usa_port').options.length = 0;
	$('usa_port').options[0] = new Option('---', '');
	ShowMap(2, 1);
	$('table-to_port').style.display = 'block';
}
function CountryClick() 
{
	hide_results();
	id = $('to_country').value;
	$('table-usa_port').style.display = 'none';
	$('usa_port').options.length = 0;
	$('usa_port').options[0] = new Option('---', '');
	if( id === '' )
	{
		$('table-to_port').style.display = 'none';
		$('to_port').options.length = 0;
		$('to_port').options[0] = new Option('---', '');
		ShowMap(1, 1);
	} else {
		to_country_id = id;
		ShowMap(2, 1);
		$('table-to_port').style.display = 'block';
	}
}
function markerPortClick(id) 
{
	hide_results();
	$('to_port').value  = id;
	to_port_id = id;

	$('table-usa_port').style.display = 'block';
	ShowMap(3, 1);
}
function PortClick() 
{
	hide_results();
	id = $('to_port').value;
	if( id === '' )
	{
		$('table-usa_port').style.display = 'none';
		$('usa_port').options.length = 0;
		$('usa_port').options[0] = new Option('---', '');
		ShowMap(2, 1);
	} else {
		to_port_id = id;
		$('table-usa_port').style.display = 'block';
		ShowMap(3, 1);
	}
}
function markerUsaPortClick(id) 
{
	hide_results();
	$('usa_port').value  = id;
	calculate(1);
}
function UsaPortClick() 
{
	hide_results();
	calculate(1);
}
function markerBorderCrossingClick(id) 
{
	hide_results();
	$('to_border_crossing').value  = id;
	calculate(1);
}
function BorderCrossingClick() 
{
	hide_results();
	calculate(1);
}
function markerYardClick(id) 
{
	hide_results();
	$('from_yard').value = id;

	var shipping_type = $('shipping_type').value;
	if(shipping_type=="I")
	{
		if($('to_country').value === '')
		{
			$('table-to_country').style.display = 'block';
			$('to_country').options.length = 0;
			$('to_country').options[0] = new Option('---', '');
			ShowMap(1, 1);
		}
	} else if(shipping_type=="B") {
		if($('to_border_crossing').value==='')
		{
			ShowMap(4, 1);
		}
	}
	calculate(0);
}
function YardClick() 
{
	hide_results();
	var shipping_type = $('shipping_type').value;
	if(shipping_type=="I")
	{
		if($('to_country').value === '')
		{
			$('table-to_country').style.display = 'block';
			$('to_country').options.length = 0;
			$('to_country').options[0] = new Option('---', '');
			ShowMap(1, 1);
		}
	} else if(shipping_type=="B") {
		if($('to_border_crossing').value==='')
		{
			ShowMap(4, 1);
		}
	}
	calculate(0);
}
function ChangeShippingType()
{
	var shipping_type 	= $('shipping_type').value; 
	var from_type 		= $('from_type').value;
	$('table-to_country').style.display = "none";
	$('table-to_port').style.display = "none";
	$('table-usa_port').style.display = "none";
	$('table-to_zip').style.display = "none";
	$('table-to_border_crossing').style.display = "none";
	hide_results();

	if( map ) {
		map.clearOverlays();
	}

	is_show = 1;
	if (shipping_type=='D') {
		map.setCenter(new GLatLng(DLat, DLng), DZoom);
		map_type = 0;
		$('table-to_zip').style.display = "block";
		if(($('from_yard').value !== "" && from_type=='yard') || (isZipValid($('from_zip').value) && from_type=='zip')) {
			is_show = 0;
		}
	} else if (shipping_type=='B') {
		map.setCenter(new GLatLng(DLat, DLng), DZoom);

		if(($('from_yard').value !== "" && from_type=='yard') || (isZipValid($('from_zip').value) === true && from_type=='zip'))
		{
			if(!mapPoint[0] || mapPoint[0].length < 1) {
				ShowMap(0, 0);
			} else {
				map_type = 4;
			}
		} else {
			map_type = 0;
		}
		$('table-to_border_crossing').style.display = "block";
	} else if (shipping_type=='I') {
		map.setCenter(new GLatLng(ILat, ILng), IZoom);
		$('table-to_country').style.display = "block";
		if($('to_country').value > 0)
		{
			$('table-to_port').style.display = "block";
			to_country_id = $('to_country').value;
			map_type = 2;
			if(!mapPoint[0] || mapPoint[0].length < 1) {
				ShowMap(0, 0);
			}
		} else {
			map_type = 1;
		}
	}
	LoadMap(map_type, is_show);
	calculate(0);
}
function ChangeVehicleType(){
	calculate(0);
}
function ChangeLocation(location)
{
	$('from_type').value = location;
	if(location=='yard')
	{
		$('container-zip').style.display = 'none';		
		$('location-zip-act').style.display = 'none';
		$('location-zip').style.display = 'inline';
		$('container-yard').style.display = 'inline';
		$('location-yard').style.display = 'none';
		$('location-yard-act').style.display = 'inline';
	} else {
		$('container-yard').style.display = 'none';
		$('location-yard-act').style.display = 'none';
		$('location-yard').style.display = 'inline';
		$('container-zip').style.display = 'inline';		
		$('location-zip').style.display = 'none';
		$('location-zip-act').style.display = 'inline';
	}
	calculate(0);
}
function set_zip()
{
	var shipping_type = $('shipping_type').value; 
	
	if (isZipValid($('from_zip').value))
	{
		if(shipping_type=='B')
		{
			if($('to_border_crossing').value==='')
			{
				ShowMap(4, 1);
			}
		} else if (shipping_type=='D') {
			null;
		} else if (shipping_type=='I') {
			if($('to_country').value === '')
			{
				$('table-to_country').style.display = 'block';
				$('to_country').options.length = 0;
				$('to_country').options[0] = new Option('---', '');
				ShowMap(1, 1);
			}
		}
		calculate(0);		
	}
}
function calculate(is_submit){
	var objRegExp;
	var h 		= $('h').value;
	var vehicle_type = $('vehicle_type').value; 
	var shipping_type = $('shipping_type').value; 
	var from_type 	= $('from_type').value;
	var from_yard	= $('from_yard').value; 
	var from_zip 	= trimWS($('from_zip').value);
	var to_zip 		= trimWS($('to_zip').value);
	var usa_port 	= $('usa_port').value;
	var to_country 	= $('to_country').value;
	var to_port		= $('to_port').value;
	var to_border_crossing = $('to_border_crossing').value;
	var purchase 	= $('purchase').value;

	if (from_type=='yard')
	{
		if(from_yard < 1)
		{
			if(is_submit)
			{
				alert(msg['facility']);
				$('from_yard').focus();
			}
			return false;
		}
	}  else if(from_type=='zip') {
		if (!isZipValid(from_zip))
		{
			if(is_submit)
			{
				alert(msg['zip']);
				$('from_zip').focus();
			}
			return false;
		}
	}
	if (shipping_type=='D') {
		if (!isZipValid(to_zip))
		{
			if(is_submit)
			{
				alert(msg['zip']);
				$('to_zip').focus();
			}
			return false;
		}
	} else if (shipping_type=='B') {
		if(to_border_crossing==='') {
			return false;
		}
	} else if (shipping_type=='I') {
		if(to_country==='') {
			return false;
		}
		if(to_port==='') {
			return false;
		}
		if(usa_port==='') {
			return false;
		}
	}
	$('order-container').style.display = "none";

	var ajaxUrl = url+'shipping-salvage-vehicles/get-rate/';
	new Ajax.Request(ajaxUrl,
	{
		method: 'get',
		evalJSON: true,
		parameters: {from_type: from_type, from_yard:from_yard, from_zip:from_zip, vehicle_type:vehicle_type, to_zip:to_zip, h:h, shipping_type:shipping_type, usa_port:usa_port, to_country:to_country, to_port:to_port, to_border_crossing:to_border_crossing, purchase:purchase},
		onSuccess: function(transport) {
			docalculate( transport.responseJSON );
		},
		onFailure: function(){}, 
		onException: function(request, ex){}
	});		
	return true;
}
function docalculate( calc ) 
{
	if ( calc ) 
	{
		if (calc.shipping_type=='D' || calc.shipping_type=='B') {
			$('total-D').style.display = "block";
			$('r_domestic_place').update(calc.domestic_place);
			$('r_domestic_price').update(calc.domestic_price);
			$('r-domestic_price').value = calc.domestic_price;
			
			$('table-total').style.display = "block";
			$('r_total').update(calc.total);
		} else {
			$('total-D').style.display = "none";
		}
		if (calc.shipping_type=='I') {
			$('total-I').style.display = "block";
			$('r_usa_port_price').update(calc.usa_port_price);
			$('r_to_port_price').update(calc.to_port_price);
			$('r_usa_port').update(calc.usa_port_name);
			$('r_usa_port2').update(calc.usa_port_name);
			$('r_to_port').update(calc.to_port_name);
			
			$('table-total').style.display = "block";
			$('r_total').update(calc.total);
			$('r-domestic_price').value = calc.usa_port_price;
			$('r-destination_price').value = calc.to_port_price;
		} else {
			$('total-I').style.display = "none";
		}
		if(calc.from_type=='yard') {
			$('r-yard').update(calc.from_yard_name);
		} else {
			$('r-yard').update(calc.domestic_place);
			$('r_domestic_place').update(calc.domestic_place);
		}
		
		$('data').value = calc.data;
		$('data_h').value = calc.data_h;
		$('order-container').style.display = "block";
		//$('link').value = calc.link;
		$('r-from_zip').value = calc.from_zip;
		$('r-to_zip').value = calc.to_zip;

		setDirection();
	}
}
function setDirection()
{
	map.clearOverlays();

	directions = new GDirections(map);
	GEvent.addListener(directions, "addoverlay", onGDirectionsShow);

	directions.clear();
	directions.load("from: "+$('r-from_zip').value+" to: "+$('r-to_zip').value+"");
}
function onGDirectionsShow()
{
	var shipping_type = $('shipping_type').value; 
	var vehicle_type = $('vehicle_type').value; 
	var from_type	= $('from_type').value; 
	var from_yard	= $('from_yard').value; 
	var from_zip	= trimWS($('from_zip').value); 
	var to_zip 		= trimWS($('to_zip').value);
	var usa_port	= $('usa_port').value;
	var to_country 	= $('to_country').value;
	var to_port		= $('to_port').value;

	if(from_type=='yard')
	{
		for ( var i = 0; i < Markers[0].length; i++ )
		{
			if (from_yard == Markers[0][i]['id'])
			{
				facility_marker = directions.getMarker(0);
				facility_marker.hide();
				f_marker = Markers[0][i]['marker'];
				map.addOverlay(f_marker);
			}
		}
	} else {
		dest_marker = directions.getMarker(0);
		d_point = dest_marker.getLatLng();
		dest_marker.hide();
		var markerIcon = new GIcon();
		markerIcon.image = "/i/icons/marker_yellow.png";
		markerIcon.shadow = "/i/icons/marker_shadow.png";
		markerIcon.iconSize = new GSize(32, 32);
		markerIcon.shadowSize = new GSize(59, 32);
		markerIcon.iconAnchor = new GPoint(15, 32);
		markerOptions = {icon: markerIcon, title: $('r_domestic_place').innerHTML};
		d_marker = new GMarker(d_point, markerOptions);
		dest_marker.hide();
		map.addOverlay(d_marker);
	}
	
	if(shipping_type=='D' || shipping_type=='B')
	{	
		dest_marker = directions.getMarker(1);
		d_point = dest_marker.getLatLng();
		dest_marker.hide();
		var markerIcon2 = new GIcon();
		markerIcon2.image = "/i/icons/marker_green.png";
		markerIcon2.shadow = "/i/icons/marker_shadow.png";
		markerIcon2.iconSize = new GSize(32, 32);
		markerIcon2.shadowSize = new GSize(59, 32);
		markerIcon2.iconAnchor = new GPoint(15, 32);
		markerOptions = {icon: markerIcon2, title: $('r_domestic_place').innerHTML};
		d_marker = new GMarker(d_point, markerOptions);
		dest_marker.hide();
		map.addOverlay(d_marker);
	
	} else if(shipping_type=='I') {
		i = 0;
		for ( i = 0; i < Markers[3].length; i++ )
		{
			if (usa_port == Markers[3][i]['id'])
			{
				usaport_marker = directions.getMarker(1);
				usaport_marker.hide();
				up_marker = Markers[3][i]['marker'];
				map.addOverlay(up_marker);
				var usaport_lat_lng = mapPoint[3][i]["pnt"];
			}
		}
		for ( i = 0; i < Markers[2].length; i++ )
		{
			if (to_port == Markers[2][i]['id'])
			{
				destport_marker = directions.getMarker(1);
				destport_marker.hide();
				dp_marker = Markers[2][i]['marker'];
				map.addOverlay(dp_marker);
				var destport_lat_lng = mapPoint[2][i]["pnt"];
				
				var polyline = new GPolyline(
				   [usaport_lat_lng, destport_lat_lng], 
				   '#fcf1a6', 
				   5,
				   1,
				   {geodesic:false});
		  		map.addOverlay(polyline);
	
			   var LatLngforDIV2 = new GLatLng((usaport_lat_lng.lat() + destport_lat_lng.lat()) / 2, (usaport_lat_lng.lng() + destport_lat_lng.lng()) / 2);
			   map.addOverlay(new Rectangle(LatLngforDIV2, $("r-destination_price").value, '#fcf1a6', 'div_price2'));
		   }
		}
		map.setCenter(new GLatLng(ILat, ILng), IZoom);
	}
	bounds = directions.getBounds();
	ne = bounds.getNorthEast();
	sw = bounds.getSouthWest();

	var LatLngforDIV = new GLatLng((ne.lat() + sw.lat()) / 2, (ne.lng() + sw.lng()) / 2);
	map.addOverlay(new Rectangle(LatLngforDIV, $("r-domestic_price").value, '#2a26d1', 'div_price'));
}
var infodivhalfwidth = 50;
var infodivhalfheight = 10;

function Rectangle (divcenterpoint, htmltxt, bg_color, div_id) {
	this.divcenterpoint_ = divcenterpoint;
	this.htmltxt_ = htmltxt;
	this.color_ = bg_color;
	this.div_id_ = div_id;
}
Rectangle.prototype = new GOverlay();
Rectangle.prototype.initialize = function(map) {
	var div = document.createElement("div");
	div.id = this.div_id_;
	div.style.border = "0px";
	div.style.background = this.color_;
	div.style.color = "#000000";
	div.style.position = "absolute";
	div.style.padding = "0px";
	div.style.margin = "0px";
	div.style.textAlign = "center";
	div.innerHTML = "<B>" + this.htmltxt_ + "</B>";
	div.style.width = (infodivhalfwidth * 2) + "px";
	div.style.height = (infodivhalfheight * 2) + "px";
	map.getPane(G_MAP_MARKER_PANE).appendChild(div);
	this.map_ = map;
	this.div_ = div;
};
Rectangle.prototype.remove = function() {
	this.div_.parentNode.removeChild(this.div_);
};
Rectangle.prototype.redraw = function(force) {
	if (!force) {
		return;
	}
	var divcntpnt = this.map_.fromLatLngToDivPixel(this.divcenterpoint_);
	this.div_.style.left = (divcntpnt.x - infodivhalfwidth) + "px";
	this.div_.style.top = (divcntpnt.y - infodivhalfheight) + "px";
};
function hide_results()
{
	$('total-D').style.display = "none";
	$('total-I').style.display = "none";
	$('table-total').style.display = "none";
	$('order-container').style.display = "none";
}
Event.observe(window, "load", function(){
	Initialize();
	ChangeShippingType();

	Event.observe('shipping_type', 'change', ChangeShippingType);
    Event.observe('vehicle_type', 'change', ChangeVehicleType);
    Event.observe('from_yard', 'change', YardClick);
    Event.observe('usa_port', 'change', UsaPortClick);
    Event.observe('to_country', 'change', CountryClick);
    Event.observe('to_port', 'change', PortClick);
    Event.observe('to_border_crossing', 'change', BorderCrossingClick);
});