/*!
 * Global Shipping Costs v1.0
 * http://globalshippingcosts/
 * calc/js/calc.js
 * Copyright (c) 2009 Oscar Valdivia & Alfonso Llanes
 *Create by: omvaldiv
 * Date: 2009-3-18
 * Revision: 0
 */
//requires jquery


//Variables
var http_request = false; 
var map; //map variable
var directions; //directions control
var Esa;
var Esa2;


//labels

window.dhx_globalImgPath="js/codebase/imgs/";
//classes 
function AdDrawerController(map){
	this.size = 129;
	this.markers = new Array();
	this.map = map;
	this.url = "json.html"
	
	
}

function LandCost(totalCost, transitTime, distance){
	this.totalCost = totalCost;
	this.transitTime = transitTime;
	this.distance = distance;
}

function OceanCost(totalCost, transitTime, distance){
	this.totalCost = totalCost;
	this.transitTime = transitTime;
	this.distance = distance;
}

function AirCost(costKilo, totalCost, transitTime, distance){
	this.costKilo = costKilo;
	this.totalCost = totalCost;
	this.transitTime = transitTime;
	this.distance = distance;
}



function Location(locationString){
	if (locationString!=""){
		var ar = locationString.split("|");
	
		this.latitude = ar[0];
		this.longitude = ar[1];
		this.latitudeLongitude = ar[0] + "," + ar[1];
		
		this.zoom = ar[2];
		this.name = ar[3];
		this.country = ar[4];
		this.description = ar[5];
		this.id = ar[6];
		
		
	}

	

}

function _prototypeLoad(){
	makeRequest(this.url, this.map);
	
}

function _prototypeDisplayList(){
}

AdDrawerController.prototype.load = _prototypeLoad;
AdDrawerController.prototype.displayList = _prototypeDisplayList;

//functions
function calculatePriceLand(distanceMiles, type ){

	$.post("../include/cost.php", {type_cost: "land" , distance_miles: distanceMiles , type : type}, function(xml) {
		var freight =  $("cost", xml).text() ;
		var transit_time = $("transit_time", xml).text();	 
		var distance = $("distance", xml).text();	 
		
		var objCost = new LandCost( freight , transit_time, distance );
		 
		displayCostLand(objCost);
	       
	});
		 
}


function calculatePriceAir(distanceNauticalMiles, loadKilos ){

	if (loadKilos > 1000){
		alert("Please, enter a load less than 1000 Kilos");
	}else{
		$.post("../include/cost.php", {type_cost: "air" , distance_nautical_miles: distanceNauticalMiles , load_kilos : loadKilos}, function(xml) {
			 var freight =  $("cost", xml).text() ;
			 var transit_time = $("transit_time", xml).text();
			 var total_cost = $("total_cost", xml).text();
			 var distance = $("distance", xml).text();	 
			 
			 var objCost = new AirCost( freight, total_cost , transit_time , distance);
	         displayCostAir(objCost);
	       
	     });
	 }
}



function calculatePriceShipNoTransit(distanceNauticalMiles, containerSize, reef , lcl){
	$.post("../include/cost.php", {type_cost: "ocean" , distance_nautical_miles: distanceNauticalMiles , container_size : containerSize, reef:reef, lcl:lcl}, function(xml) {
		var freight =  $("cost", xml).text() ;
		var transit_time = "";
		var distance = "";	 
		
		
		var objCost = new OceanCost( freight , transit_time, distance );
        displayCostShipNoTransit(objCost) ;
       
     });
}


function calculatePriceShip(distanceNauticalMiles, containerSize, reef , lcl){
	$.post("../include/cost.php", {type_cost: "ocean" , distance_nautical_miles: distanceNauticalMiles , container_size : containerSize, reef:reef, lcl:lcl}, function(xml) {
		var freight =  $("cost", xml).text() ;
		var transit_time = $("transit_time", xml).text();
		var distance = $("distance", xml).text();	 
		
		
		var objCost = new OceanCost( freight , transit_time, distance );
        displayCostShip(objCost) ;
       
     });
}



function callCostLand(){

	
	
	pointOriginLand = new GLatLng(directions.getGeocode(0).Point.coordinates[1],
                          directions.getGeocode(0).Point.coordinates[0]);
						  
	pointDestinationLand = new GLatLng(directions.getGeocode(1).Point.coordinates[1],
                          directions.getGeocode(1).Point.coordinates[0]);
	
	
	var tinyIcon = getTinyIcon();
		
		
	var markerOriginEsaLand = new GMarker(pointOriginLand, tinyIcon);
	var markerDestinationEsaLand = new GMarker(pointDestinationLand, tinyIcon);
	
	
	Esa.setCenter(pointOriginLand,16);
	Esa2.setCenter(pointDestinationLand,16);
	
	Esa.addOverlay(markerOriginEsaLand);
	Esa2.addOverlay(markerDestinationEsaLand);

	
	GEvent.addListener(markerOriginEsaLand, "click", function() {
		markerOriginEsaLand.openInfoWindowHtml(getServicesLand(pointOriginLand));
	});
		
		
	GEvent.addListener(markerDestinationEsaLand, "click", function() {
		 markerDestinationEsaLand.openInfoWindowHtml(getServicesLand(pointDestinationLand));
	});
		
	Esa.openInfoWindow(Esa.getCenter(),getServicesLand(pointOriginLand));
	Esa2.openInfoWindow(Esa2.getCenter(),getServicesLand(pointDestinationLand));


	distanceMiles = convertMeterToMiles(directions.getDistance().meters);
	
	var type = (document.getElementById("land_type_ltl").checked) ? "LTL" : "TL" ;
	
	calculatePriceLand(distanceMiles, type);
	
	
	
}

function clearAllMaps(){
	map.clearOverlays();
	Esa.clearOverlays();
	Esa2.clearOverlays();
	
}


function clearFields(){
	var str;
	for(var i=0; i< arguments.length; i++){
      //check if there is another value
	  str = arguments[i].split(":")
	  
	  if (str.length > 1){
		$("#" + str[0]).val(str[1]);
	  }else
		$("#" + str[0]).val('');
	  
	}

}

function convertMeterToMiles(meters){
	var constant = 0.000621371192// miles
	return meters * constant;
	
}


function convertCubicFeetToCubicMeter(feets){
	var constant = 0.0283168466// cubic meters
	return feets * constant;
	
}

function convertCubicMeterToCubicFeet(meters){
	var constant = 35.3146667// cubic feet
	return meters * constant;
	
}

function convertPoundToKilos(pounds){
	var constant = 0.45359237// k
	return pounds * constant;
	
}

function convertKilosToPounds(kilos){
	var constant = 2.20462262// pounds
	return kilos * constant;
	
}


function createLineAir(){
	createLineAirS(origin_air.getSelectedValue(), destination_air.getSelectedValue());
}
function createLineAirS(origin_value, destination_value){

	var originAir = new Location(origin_value);
	var destinationAir = new Location(destination_value);


	$("#schedule_panel_1").hide();
		$("#schedule_panel_2").hide();
		$("#schedule_panel_3").hide();
		$("#schedule_panel_4").hide();
		$("#schedule_panel_5").hide();
		$("#schedule_panel_6").hide();
		$("#schedule_panel_7").hide();
		$("#schedule_panel_8").hide();

	if (originAir.latitudeLongitude!='' && destinationAir.latitudeLongitude!=''){
		if (originAir.latitudeLongitude==destinationAir.latitudeLongitude) {
			alert(SELECT_DIFF_DEST);
			return;
		}
		
		
		if(document.getElementById("commodity_name_air").value=="" || document.getElementById("commodity_name_air").value==CALC_LABEL_OCEAN_COMMODITY_NAME_TYPE){
			alert(CALC_MSG_MISSING_COMMODITY);
			return;
		}
		
		clearAllMaps();
		var tinyIcon = getTinyIcon();
		
		var pointOriginAir = getPoint(originAir.latitudeLongitude);
		var pointDestinationAir = getPoint(destinationAir.latitudeLongitude)
		
		distanceNauticalMiles = getNauticalMiles(pointOriginAir.distanceFrom(pointDestinationAir));
		
		
		
		var markerOriginAir = new GMarker(pointOriginAir);
		var markerDestinationAir = new GMarker(pointDestinationAir);
		
		var markerOriginEsaAir = new GMarker(pointOriginAir,tinyIcon);
		var markerDestinationEsaAir = new GMarker(pointDestinationAir,tinyIcon);
		
		
		
		
		map.panTo(pointOriginAir)
		
		
		map.addOverlay(markerOriginAir);
		map.addOverlay(markerDestinationAir);
		
		
		Esa.addOverlay(markerOriginEsaAir);
		Esa2.addOverlay(markerDestinationEsaAir);
		
		
		
		var polyline = createPolyLine(pointOriginAir, pointDestinationAir);
		map.addOverlay(polyline);
		
		Esa.setCenter(pointOriginAir, parseInt(originAir.zoom));
		Esa2.setCenter(pointDestinationAir, parseInt(destinationAir.zoom));
		
		
		GEvent.addListener(markerOriginEsaAir, "click", function() {
		  markerOriginEsaAir.openInfoWindowHtml(getServicesAir(pointOriginAir, originAir));
		});
		
		
		GEvent.addListener(markerDestinationEsaAir, "click", function() {
		  markerDestinationEsaAir.openInfoWindowHtml(getServicesAir(pointDestinationAir, destinationAir));
		});
		
		Esa.openInfoWindow(Esa.getCenter(),getServicesAir(pointOriginAir, originAir));
		Esa2.openInfoWindow(Esa2.getCenter(),getServicesAir(pointDestinationAir, destinationAir));
		
		var load_kilos = document.getElementById("load_kilos").value;
		
		
		
		log_air(	originAir.name , 
					destinationAir.name, 
					$("#load_kilos").val(), 
					"Kilos",
					$("#commodity_name_air").val()
				);
		
		
		calculatePriceAir(distanceNauticalMiles, load_kilos);
		
		
	}else
		alert(LOCATION_ORIGIN_DESTINATION_BLAMK_MSG)

}





function createLineLand(){
	createLineLandS(document.getElementById("origin_land").value, document.getElementById("destination_land").value);
}



function createLineLandS(origin_val, destination_val){
	var originLandSel = origin_val;
	var destinationlandSel = destination_val;
	
	
	$("#schedule_panel_1").hide();
		$("#schedule_panel_2").hide();
		$("#schedule_panel_3").hide();
		$("#schedule_panel_4").hide();
		$("#schedule_panel_5").hide();
		$("#schedule_panel_6").hide();
		$("#schedule_panel_7").hide();
		$("#schedule_panel_8").hide();
	
	if (originLandSel!='' && destinationlandSel!=''){
		
		if (originLandSel==destinationlandSel) {
			alert(SELECT_DIFF_DEST);
			return;
		}
		
		if(document.getElementById("commodity_name_land").value=="" || document.getElementById("commodity_name_land").value==CALC_LABEL_OCEAN_COMMODITY_NAME_TYPE){
			alert(CALC_MSG_MISSING_COMMODITY);
			return;
		}
		
		
		clearAllMaps();
		
		log_land(	origin_val , 
					destination_val, 
					document.getElementById("land_type_ltl").checked ? "LTL" : "TL" , 
					$("#ltl_weight").val(), 
					$("#ltl_weight_unit").val(), 
					$("#ltl_volume").val(), 
					$("#ltl_volume_unit").val(),
					$("#commodity_name_land").val()
				);
		
		
		//directions
		directions = new GDirections(map);
		setDirections(originLandSel, destinationlandSel);
		
		GEvent.addListener(directions, "error", handleErrors);
		GEvent.addListener(directions, 'load', callCostLand);
		
	}
}


function createLineShip(){
	createLineShipS(origin1.getSelectedValue(), destination1.getSelectedValue());
}





function drawMiaKingston(dest){
	

	

	
	var sw = new GLatLng(17.9812455554903, -80.15804091610204);
	
	var ne = new GLatLng(25.77278268537193, -63.04502379041386);
	
	var bounds = new GLatLngBounds(sw, ne);
	
	var mapZoomLevel = map.getBoundsZoomLevel(bounds);
	
	var mapCenter = new GLatLng(21.877014120431113, -71.60153235325795)
	
	map.setCenter(mapCenter, mapZoomLevel);



	
	
	var polyline1_1 = new GPolyline.fromEncoded({
	  color: "#0000ff",
	  weight: 4,
	  opacity: 0.8,
	  points: "{vh|CxzfhNbsB}wHpjPuiBj`wDizWxp{F{f_DhuqBunkApqz@crqC`l_CowiD~xpGyojWhweFubdb@pimD}cqUlrqAulcB_z@s~OauBobE",
	  levels: "PJKMIOLPMKMLIP",
	  zoomFactor: 2, 
	  numLevels: 18
	});


	
								
	var polyline1_2 = new GPolyline.fromEncoded({
	  color: "#0000ff",
	  weight: 4,
	  opacity: 0.8,
	  points: "kr|lBfrx_Kv}Cne@tcc@byJlqoAgiOlb_@a{k@}nAksL{eDgeAupDbV",
	  levels: "PFKMLJHP",
	  zoomFactor: 2, 
	  numLevels: 18
	});

	
	
	var polyline1_3 = new GPolyline.fromEncoded({
	  color: "#0000ff",
	  weight: 4,
	  opacity: 0.8,
	  points: "ysngBhonxJFhNm[n|@mm@~qAarBfeE{iDnkr@_wMxgo@a]~yThzCxmLd~CrgFvf@zlDihApfFgsCdeAumCh^u~D~f@",
	  levels: "PEFCIIKJHGKJGBP",
	  zoomFactor: 2, 
	  numLevels: 18
	});


	
	
	var polyline1_4 = new GPolyline.fromEncoded({
	  color: "#0000ff",
	  weight: 4,
	  opacity: 0.8,
	  points: "sb~nA`o}jJyiA~`@qvNfjGsuu@leZwlzBpt}@wkdLlrgB{rfB|mrAwvPxcnAqaPhprAqeNhtKyvIs{Fo}CmnD_dBaaDpyCuyH",
	  levels: "PEEFMNMGMLHGKP",
	  zoomFactor: 2, 
	  numLevels: 18
	});



	
	
	var polyline1_5 = new GPolyline.fromEncoded({
	  color: "#0000ff",
	  weight: 4,
	  opacity: 0.8,
	  points: "sin~@xiivJ|AfzAmr@zk@efRva^csSzdQevPtdFuyg@qdOoz~CglyAcymDgpcFuwj@sjv@i}UwfWs~G{kC}oLgbAq_CuO{b@kUtD}`@rFkTvUsJ",
	  levels: "PHGKINJNGKJHDIHDFP",
	  zoomFactor: 2, 
	  numLevels: 18
	});


	
	
	var polyline1_6 = new GPolyline.fromEncoded({
	  color: "#0000ff",
	  weight: 4,
	  opacity: 0.8,
	  points: "oun~@|jivJ~kCraDfxL`}VtzSz{p@niHbmGnnLrdDtlMoJvbJihPmk@czkBncLe`ZpuiDgb_Ens`G_`rJtxrGistPvzb@}la@z{T_aDh}HctB~nGcwLdvBq|@hw@aTze@gGduA`Bb{@nWfcAv`AbM`h@rQdaAl_@lsDfd@bu@",
	  levels: "PHILIJNKKMLNMJGJHLDFHFJCFGP",
	  zoomFactor: 2, 
	  numLevels: 18
	});



	
	
	var polyline1_7 = new GPolyline.fromEncoded({
	  color: "#0000ff",
	  weight: 4,
	  opacity: 0.8,
	  points: "ibnb@vruoIsz@_y@aQczAqv@}sCqnA_nBkqAyg@auAbM}y@`[yuD~mD_}DtoKshM`p_@ko^n~jDgu~@jkpEycp@~~nAwlNv~uAr]h\\fTtAfeAPrcBsD",
	  levels: "PGFGJHFLIFLKLLJFGDP",
	  zoomFactor: 2, 
	  numLevels: 18
	});


	
	
	/*var polyline1_8 = new GPolyline.fromEncoded({
	  color: "#0000ff",
	  weight: 4,
	  opacity: 0.8,
	  points: "monh@hs`bJa`CbEgjBaCsY[{p@z@utM|pF{vQ`sT}mw@n}Mm{uBlkz@ysjLrhhHibfFlvoEeq`AjjnGw~lCfpzC{d{Ohoec@sqtLx}hf@wbv@niyBku~@vebAiqB|t@",
	  levels: "PE@DIJJKMLPMMMMLHP",
	  zoomFactor: 2, 
	  numLevels: 18
	});
*/
	
	
	
	
	var polyline1_8 = new GPolyline.fromEncoded({
  color: "#0000ff",
  weight: 4,
  opacity: 0.8,
  points: "aknh@hy`bJmpFfe@i`DxjAw~Bl{Aeik@~|ZssSre@qh`UrzgKklvAzeqH}qia@vphrAi|hBl}yD}um@rtg@e~[nwKk`Td~Gg`GkhE",
  levels: "PGIFJJPMNMKEKP",
  zoomFactor: 2, 
  numLevels: 18
});


	for (var i =1 ; i <= dest ; i++){
	
		eval("map.addOverlay(polyline1_"+i+")");
		
	}
		
	
		
	
	
	$("#schedule_panel_" + dest).show();


	
	

	
}




function createLineShipS(coordinatesOrigin, coordinatesDestination){
	
	var origin = new Location(coordinatesOrigin);
	var destination = new Location(coordinatesDestination);

	
	
	if (origin.latitudeLongitude!='' && destination.latitudeLongitude!=''){
	
		if (origin.latitudeLongitude==destination.latitudeLongitude) {
			alert(SELECT_DIFF_DEST);
			return;
		}
		
		if(document.getElementById("commodity_name").value=="" || document.getElementById("commodity_name").value==CALC_LABEL_OCEAN_COMMODITY_NAME_TYPE){
			alert(CALC_MSG_MISSING_COMMODITY);
			return;
		}
			
		
		clearAllMaps();
		
		var pointOrigin = getPoint(origin.latitudeLongitude);
		var pointDestination = getPoint(destination.latitudeLongitude);
		
		distanceNauticalMiles = getNauticalMiles(pointOrigin.distanceFrom(pointDestination));
		
		
		
		var markerOrigin = new GMarker(pointOrigin);
		var markerDestination = new GMarker(pointDestination);
		
		
		var tinyIcon = getTinyIcon();
		
		
		var markerOriginEsa = new GMarker(pointOrigin, tinyIcon);
		var markerDestinationEsa = new GMarker(pointDestination, tinyIcon);
		
		
		map.panTo(pointOrigin)
		
		
		map.addOverlay(markerOrigin);
		map.addOverlay(markerDestination);
		
		Esa.addOverlay(markerOriginEsa);
		Esa2.addOverlay(markerDestinationEsa);
		
		$("#schedule_panel_1").hide();
		$("#schedule_panel_2").hide();
		$("#schedule_panel_3").hide();
		$("#schedule_panel_4").hide();
		$("#schedule_panel_5").hide();
		$("#schedule_panel_6").hide();
		$("#schedule_panel_7").hide();
		$("#schedule_panel_8").hide();
		
		var blnRoute = false;
		
		if (origin.latitudeLongitude == "25.77206802368164,-80.16556549072266"){
			
			
			var dests = 0;
			blnRoute = true;
			
			if ( destination.latitudeLongitude == "18.01285552978516,-63.04311370849609")
				dests = 1;
				
			if ( destination.latitudeLongitude == "17.29393768310547,-62.72249221801758")
				dests = 2;
			
			
			if ( destination.latitudeLongitude == "17.11979293823242,-61.84770584106445")
				dests = 3;
			
			if ( destination.latitudeLongitude == "13.08333301544189,-59.59999847412109")
				dests = 4;
				
			if ( destination.latitudeLongitude == "10.40175724029541,-61.49034881591797")
				dests = 5;
			
			if ( destination.latitudeLongitude == "5.81666660308838,-55.15000152587891")
				dests = 6;
				
			if ( destination.latitudeLongitude == "6.81666660308838,-58.16666793823242")
				dests = 7;
			
			if ( destination.latitudeLongitude == "17.96666717529297,-76.80000305175781")
				dests = 8;
				
				
			if (dests > 0 )
				drawMiaKingston(dests);
		
		} else{
		
			var polyline = createPolyLine(pointOrigin, pointDestination);
			map.addOverlay(polyline);
		}
		
		
		
		Esa.setCenter(pointOrigin, parseInt(origin.zoom));
		Esa2.setCenter(pointDestination, parseInt(destination.zoom));
		
		
		GEvent.addListener(markerOriginEsa, "click", function() {
		  markerOriginEsa.openInfoWindowHtml(getServicesShip(pointOrigin, origin));
		});
		
		
		GEvent.addListener(markerDestinationEsa, "click", function() {
		  markerDestinationEsa.openInfoWindowHtml(getServicesShip(pointDestination, destination));
		});
		
		Esa.openInfoWindow(Esa.getCenter(),getServicesShip(pointOrigin, origin));
		Esa2.openInfoWindow(Esa2.getCenter(),getServicesShip(pointDestination, destination));
		
		
		var container_size = document.getElementById("container_size").value;
		
		var lcl_val = document.getElementById("ship_type_lcl").checked ? "true" : "false";
		
		
		
		//log data
		var reef = document.getElementById("calc_reef").checked ? "true" : "false"
		
		log_ocean(	origin.name , 
					destination.name, 
					$("#commodity_name").val(), 
					$("#container_size").val(), 
					document.getElementById("ship_type_lcl").checked ? "LCL" : "CL" , 
					$("#lcl_weight").val(), 
					$("#lcl_weight_unit").val(), 
					$("#lcl_volume").val(), 
					$("#lcl_volume_unit").val()
				);
		
if (blnRoute){
		
	calculatePriceShipNoTransit(distanceNauticalMiles, container_size, reef, lcl_val );
		
} else{
		
		
			calculatePriceShip(distanceNauticalMiles, container_size, reef, lcl_val );
		}
		
		
		
		
		
		
	}else
		alert(LOCATION_ORIGIN_DESTINATION_BLAMK_MSG)

		
}



function createPolyLine(point1, point2){

	
	var polyOptions = {geodesic:true};
	var polyline = new GPolyline([ point1, point2 ], "#FF0000", 3, 0.5, polyOptions);
	 
	
	return polyline;
}



function diplayAds(markers){
	var arr = new Array();
	arr.push(markers.company);
	var length = arr.length;
	
	var scmd = "<span>Sponsors:</span><ul>";
	for (i=0 ; i <= length ; i ++){
		scmd += "<li>"+ markers.company[i].name +"<br>"+markers.company[i].location+"</li>";
		
		
	}
	scmd +="</ul>"
	
	var divPanel = document.getElementById("ad_panel");
	divPanel.innerHTML = scmd;
	
}






function displayCostAir(obj){
	var lcost = "<h3 class='cost_result'>"+ LABEL_FREIGHT +": &nbsp;$" + obj.costKilo + " " + LABEL_PER_KILO+ "</h3>";
	lcost +="<h3 class='cost_result'>"+ LABEL_TOTAL_FREIGHT +": &nbsp;$" + obj.totalCost + "</h3>";
	lcost +="<h3 class='cost_result'>"+ LABEL_TRANSIT_TIME +": &nbsp;" + obj.transitTime + " " + LABEL_HRS+"</h3>";
	lcost +="<h3 class='cost_result'>"+ LABEL_DISTANCE +": &nbsp;" + obj.distance + " " + LABEL_KNOTS+"</h3><br>";
	
	document.getElementById("cost_label_air").innerHTML = lcost;
}

function displayCostLand(obj){
	var lcost = "<h3 class='cost_result'>"+ LABEL_FREIGHT +": &nbsp;$" + obj.totalCost + "</h3>"
	lcost +="<h3 class='cost_result'>"+ LABEL_TRANSIT_TIME +": &nbsp;" + obj.transitTime + " " + LABEL_DAYS + "</h3>";
	lcost +="<h3 class='cost_result'>"+ LABEL_DISTANCE +": &nbsp;" + obj.distance + " " + LABEL_MILES + "</h3><br>";
	
	document.getElementById("cost_label_land").innerHTML = lcost;
}

function displayCostShip(obj){
	var lcost = "<h3 class='cost_result'>"+ LABEL_FREIGHT +": &nbsp;$" + obj.totalCost + "</h3>"
	lcost +="<h3 class='cost_result'>"+ LABEL_TRANSIT_TIME +": &nbsp;" + obj.transitTime + " " + LABEL_DAYS + "</h3>";
	lcost +="<h3 class='cost_result'>"+ LABEL_DISTANCE +": &nbsp;" + obj.distance + " " + LABEL_KNOTS+" </h3><br>";
	
	document.getElementById("cost_label_ship").innerHTML = lcost;
}


function displayCostShipNoTransit(obj){
	var lcost = "<h3 class='cost_result'>"+ LABEL_FREIGHT +": &nbsp;$" + obj.totalCost + "</h3>"
	
	document.getElementById("cost_label_ship").innerHTML = lcost;
}

function draw(markers, map){
	var arr = new Array();
	arr.push(markers.company);
	var length = arr.length;
	
	
	for (i=0 ; i <= length ; i ++){
			map.addOverlay( getMarker(markers.company[i]) );
	}
	
	
}


function drawMap(){
	var widthMapDiv = getDocumentWidth() - 420;
	var heightMapDiv = getDocumentHeight() - 250;
	
	
	var html = "<table border=0 cellpadding=0 cellspacing=0 style='position:absolute; left:340px; top:110px; border: solid 1px #97a5b0;'><tr><td colspan=2 style='border-bottom: solid  1px #97a5b0;'><div id='map' style='width:" + 600 + "px; height:" + 400 + "px'>map loading...</div></td></tr>";
		html += "<tr><td><div id='esa' style='width:" + 300 + "px; height:" + 400 + "px'>map loading...</div></td><td style='border-left: solid 1px #97a5b0;'><div id='esa2' style='width:" + 300 + "px; height:" + 400 + "px'>map loading...</div></td></table>"

	document.write(html);
	
}

function getContents() {
	
  if (http_request.readyState == 4) {
	
      if (http_request.status == 200) {
			
          markers = json_parse(http_request.responseText);
		  draw(markers, map);
		  diplayAds(markers);
      } else {
          alert('There was a problem with the request.');
      }
  }
  
  
} 

function getDocumentHeight(){
	var hght;
	if (document.all) { 

		hght=document.documentElement.clientHeight;

	} else {
		hght = window.screen.height;
	}


	return  window.screen.height;
};

function getDocumentWidth(){
	if (document.body.scrollWidth)
	return document.body.scrollWidth;
	var w = document.documentElement.offsetWidth;
	if (window.scrollMaxX)
	w += window.scrollMaxX;
	return w;
};

function getMarker(company){
	var point = getPoint(company.latitude + "," + company.longitude);
	
	var iconm = new GIcon(G_DEFAULT_ICON);
	iconm.image =  "icons/orange-dot.png";
	iconm.iconSize = new GSize(32, 32);
	
	var mrk = new GMarker(point, iconm);
	
	
	
	return mrk;

}

function getNauticalMiles(distanceMeters){
	return distanceMeters/parseFloat(1852);

}

function getPoint(latLong){
	var indx = latLong.indexOf(",");
	var latitude = latLong.substring(0,indx);
	var longitude = latLong.substring(indx+1, latLong.length - 1);
	
	
	
	var latLong = new GLatLng(latitude,longitude);
	
	
	return latLong;
}




function getServicesLand(point){
	return "<a href='#'>"+LABEL_LIST_SERVICES+"...</a>";
}

function getServicesAir(point, obj){
	return "<font class=location>"+obj.name + "</font><br><font class=location_country>" + obj.country + "</font><br><a class=location_ref href=# onclick=\"open_info_win("+ obj.id +")\">"+LABEL_LIST_SERVICES+"...</a>";
}

function getServicesShip(point, obj){
	return "<font class=location>"+obj.name + "</font><br><font class=location_country>" + obj.country + "</font><br><a class=location_ref href=# onclick=\"open_info_win("+ obj.id +")\">"+LABEL_LIST_SERVICES+"...</a>";
}



function getTinyIcon(){
	// "tiny" marker icon
	var icon = new GIcon();
	icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
	icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	icon.iconSize = new GSize(12, 20);
	icon.shadowSize = new GSize(22, 20);
	icon.iconAnchor = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);

	return icon;
}





function handleErrors(){
  if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
    alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + directions.getStatus().code);
  else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
    alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directions.getStatus().code);
  else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
    alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + directions.getStatus().code);
  else if (directions.getStatus().code == G_GEO_BAD_KEY)
    alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directions.getStatus().code);
  else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
    alert("A directions request could not be successfully parsed.\n Error code: " + directions.getStatus().code);
  else alert("An unknown error occurred.");
}



function hideAllLayer(){
	document.getElementById("ship_layer").style.display = 'none';
	document.getElementById("air_layer").style.display = 'none';
	document.getElementById("land_layer").style.display = 'none';
	
}


function isNumeric(sText)

{
   
   if (!sText)
		return false;
		
		
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;


   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}

function log_land(_from, _to, _type , _weight, _weight_unit, _volume , _volume_unit, _commodity_name){
	
	$.post("log.php", {	type_log: "land" , 
									from: _from , 
									to : _to, 
									type : _type,
									weight : _weight,
									weight_unit : _weight_unit,
									volume : _volume,
									volume_unit:_volume_unit,
									commodity_name : _commodity_name
								});
	
}


function log_air(_from, _to, _load, _load_unit, _commodity_name){
	
	$.post("log.php", {	type_log: "air" , 
									from: _from , 
									to : _to, 
									load : _load,
									load_unit : _load_unit,
									commodity_name : _commodity_name
								});
	
}



function log_ocean(_from, _to, _commodity_name, _container_size, _type , _weight, _weight_unit, _volume , _volume_unit){
	
	$.post("log.php", {	type_log: "ocean" , 
									from: _from , 
									to : _to, 
									commodity_name : _commodity_name , 
									container_size : _container_size, 
									type : _type,
									weight : _weight,
									weight_unit : _weight_unit,
									volume : _volume,
									volume_unit : _volume_unit
								});
	
}



function makeRequest(url, map) {
 
  if (window.XMLHttpRequest) { // Mozilla, Safari, IE7...
      http_request = new XMLHttpRequest();
  } else if (window.ActiveXObject) { // IE6 and older
      http_request = new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  http_request.onreadystatechange = this.getContents;
  http_request.open('GET', url, true);
  http_request.send(null);

} 

function open_info_win(id){
	
	$("#info_description").load("info.php?id=" + id + "&lang=");
	$("#info_description").dialog({
			title: "", 
			height: 400 , 
			width: 640, 
			modal: true, 
			resizable: false, 
			draggable:false
	});
}


var containers = new Array("20","40","45"); 

function addOption(selectbox,text,value ){
	var optn = document.createElement("OPTION");
	optn.text = text;
	optn.value = value;
	selectbox.options.add(optn);
}

function removeAllOptions(selectbox){
	var i;
	
	for(i=selectbox.options.length-1;i>=0;i--)
	{
		selectbox.remove(i);
	}
}



function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
} 


function setDirections(fromAddress, toAddress) {
  directions.load("from: " + fromAddress + " to: " + toAddress,
  { "locale":"en_US" , "getSteps":true});
}

function selectedTab(obj){
	alert(obj.id)
}

function showLayer(layer){

	hideAllLayer();
	document.getElementById(layer + "_layer").style.display = 'block';
}

function show_registration_dialog(){
	$("#register_dialog").html(must_reg_str);
	
	$("#register_dialog").dialog({
			title: "", 
			height: 400 , 
			width: 640, 
			modal: true, 
			resizable: false, 
			draggable:false
	});
		
	
	
}


function show_help_dialog(text){

	
	$("#help_dialog").html("<table><tr><td>" + text + "</td></tr></table>");
	
	$("#help_dialog").dialog({
			title: "Help", 
			height: 400 , 
			width: 500, 
			modal: true, 
			resizable: false, 
			draggable:false
	});
	
	
}


function updateHash() {
       var curcent = map.getCenter();
       var curzoom = map.getZoom();
       window.location.hash = "#lat=" + curcent.lat().toFixed(5) + "&lon=" + curcent.lng().toFixed(5) +"&zoom=" + 

		map.getZoom();
};
