var Markers		= new Array();
var mapPoint 	= new Array();
var direction   = new Array();
var directions;

var config = {
	"lang_id": 1,
	"showTotalOnly": false
};

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;
}

function mapsLoaded() {

	if (GBrowserIsCompatible())
	{
		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.copy = function()
		{
			return new Rectangle(this.divcenterpoint_, this.htmltxt_, this.color_, this.div_id_);
		}

		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";
		}

		if (config.maps.field)
		{
			config.maps.map = new google.maps.Map2(config.maps.field);

			config.maps.map.enableScrollWheelZoom();
			config.maps.map.addControl(new GLargeMapControl());
			config.maps.map.addControl(new GScaleControl());
			config.maps.map.addControl(new GMapTypeControl());

			if ((config.maps.settings.latitude) &&
				(config.maps.settings.longitude) &&
				(config.maps.settings.zoom))
			{
				config.maps.map.setCenter(
					new google.maps.LatLng(
						config.maps.settings.latitude,
						config.maps.settings.longitude
					),
					config.maps.settings.zoom
				);
			}
			config.maps.loaded = true;
		}
	}

	generateCalculator();
}

function loadMaps() {
	if (config.maps.field)
	{
		google.load("maps", "2.x", {"callback" : mapsLoaded});
	}
}

function initMapLoader() {
	var script = document.createElement("script");
	script.src = "http://www.google.com/jsapi?key=" + config.maps.key + "&callback=loadMaps";
	script.type = "text/javascript";
	document.getElementsByTagName("head")[0].appendChild(script);
}

function ShowMarkers(map_type) 
{
	var dohide = 0;
	var doshow = 0;
	for (var t = 2; t < 6; 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 == 1) {
		zoomMap(map_type);
	}
	if ((doshow == 1) && (dohide == 0))
	{
		return 1;
	}
	if ((doshow == 0) && (dohide == 1))
	{
		return 2;
	}
	if ((doshow == 1) && (dohide == 1))
	{
		return 3;
	}
	return 0;
}

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());
		}
		for (var i=0; i< direction.length; i++) 
		{
			bounds.extend(direction[i].marker.getLatLng());
		}
		if ((direction.length + Markers[map_type].length) > 1) 
		{
			var zoom = config.maps.map.getBoundsZoomLevel(bounds);
			if ((direction.length + Markers[map_type].length) == 2 && zoom > 1) 
			{
				zoom--;
			}
			config.maps.map.setZoom(zoom);
		} else {
			config.maps.map.setZoom(10);
		}
	} else {
		config.maps.map.setZoom(10);
	}

	config.maps.map.setCenter(bounds.getCenter());
}

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])
			{
				config.maps.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 CreateMarker(id, point, name, map_type) 
{
	markerIcon = new GIcon();
	markerIcon.shadow = "/images/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 == 2) {
		markerIcon.image = "/images/icons/marker_red.png";
	} else if (map_type == 5) {
		markerIcon.image = "/images/icons/marker_blue.png";
	} else if (map_type == 4) {
		markerIcon.image = "/images/icons/marker_green.png";
	} else if (map_type == 3) {
		markerIcon.image = "/images/icons/marker_yellow.png";
	}
	
	markerOptions = { icon: markerIcon, title: name };
    var marker = new GMarker(point, markerOptions);

	if (map_type == 2) {
        GEvent.addListener(marker, "click", function() {
			jQuery('#calc_data1_select').find("option[value='" + id + "']").attr("selected", "selected");
			jQuery('#calc_data1_select').change();
        });
	} else if (map_type == 3) {
        GEvent.addListener(marker, "click", function() {
			jQuery('#calc_data2_select').find("option[value='" + id + "']").attr("selected", "selected");
			jQuery('#calc_data2_select').change();
        });
	} else if (map_type == 4) {
        GEvent.addListener(marker, "click", function() {
			jQuery('#calc_data3_select').find("option[value='" + id + "']").attr("selected", "selected");
			jQuery('#calc_data3_select').change();
        });
	} else if (map_type == 5) {
        GEvent.addListener(marker, "click", function() {
			jQuery('#calc_data4_select').find("option[value='" + id + "']").attr("selected", "selected");
			jQuery('#calc_data4_select').change();
        });
	}
    return marker;
}

function setDirections(data)
{
	var old_key = -1;
	var i = 0;

	for(var key in data)
	{
		if ((data[key].fromLatLng) && (data[key].toLatLng))
		{
			color = '#ffffff';
			if (data[key].type == 3)
			{
				color = '#a6f1fc';
			}
			if (data[key].type == 4)
			{
				color = '#fcf1a6';
			}
			direction[i] = new Object();

			direction[i].polyline = new GPolyline([data[key].fromLatLng, data[key].toLatLng], color, 5, 1, {geodesic:false});
			config.maps.map.addOverlay(direction[i].polyline);

			direction[i].marker = CreateMarker(data[key].fromId, data[key].fromLatLng, data[key].fromName, data[key].type);
			config.maps.map.addOverlay(direction[i].marker);

			var LatLngforDIV2 = new GLatLng((data[key].fromLatLng.lat() + data[key].toLatLng.lat()) / 2, (data[key].fromLatLng.lng() + data[key].toLatLng.lng()) / 2);

			direction[i].pricebox = new Rectangle(LatLngforDIV2, "$" + data[key].price + " USD", color, 'div_price' + key);
			config.maps.map.addOverlay(direction[i].pricebox);

			old_key = key;
			i++;
		}
	}

	if (old_key != -1)
	{
		var key = direction.length;
		direction[key] = new Object();
		direction[key].marker = CreateMarker(data[old_key].toId, data[old_key].toLatLng, data[old_key].toName, data[old_key].type + 1);
		config.maps.map.addOverlay(direction[key].marker);
	}
}

function clearDirections()
{
	for(var key in direction)
	{
		config.maps.map.removeOverlay(direction[key].marker);
		if (direction[key].polyline)
		{
			config.maps.map.removeOverlay(direction[key].polyline);
		}
		if (direction[key].pricebox)
		{
			config.maps.map.removeOverlay(direction[key].pricebox);
		}
		direction[key] = null;
	}
	direction = new Array();
}

function zoomDirections()
{
	var bounds = new GLatLngBounds();

	for (var i=0; i< direction.length; i++) 
	{
		bounds.extend(direction[i].marker.getLatLng());
	}
	if (direction.length > 1) 
	{
		var zoom = config.maps.map.getBoundsZoomLevel(bounds);
		if (direction.length == 2 && zoom > 1) 
		{
			zoom--;
		}
		config.maps.map.setZoom(zoom);
	} else {
		config.maps.map.setZoom(10);
	}

	config.maps.map.setCenter(bounds.getCenter());
}

function initCalculator(newConfig)
{
	if (!config.lang_id)
	{
		config.lang_id = 1;
	}

	if (!config.maps)
	{
		config.maps = {};
	}

	config.maps.init = false;
	config.maps.loaded = false;

	if (typeof newConfig == "object")
	{
		if (!newConfig.lang_id)
		{
			newConfig.lang_id = config.lang_id;
		}

		config = newConfig;

		if (!config.maps)
		{
			config.maps = {};
		}

		config.maps.init = false;
		config.maps.loaded = false;

		if ((config.maps.key) && (config.maps.field))
		{
			if (!config.maps.settings)
			{
				config.maps.settings = {
//					"latitude": 1,
//					"longitude": 1,
//					"zoom": 1
				};
			}
			initMapLoader();
			config.maps.init = true;
		}
	}

	if (!config.maps.init)
	{
		generateCalculator();
	}
}

function generateCalculator()
{
	jQuery("#calc_shipping_select").change(function(){
		params = {
			"action": "changeShipping",
			"id": jQuery(this).val(),
			"langid": config.lang_id,
			"type": 1
		}
		changeFields(this, params);
	});
	jQuery("#calc_vehicle_select").change(function(){
		params = {
			"action": "changeVehicle",
			"id": jQuery(this).val(),
			"langid": config.lang_id,
			"type": 2
		}
		changeFields(this, params);
	});
	jQuery("#calc_data1_select").change(function(){
		params = {
			"action": "changeData1",
			"id": jQuery(this).val(),
			"langid": config.lang_id,
			"type": 3
		}
		changeFields(this, params);
	});
	jQuery("#calc_data2_select").change(function(){
		params = {
			"action": "changeData2",
			"id": jQuery(this).val(),
			"langid": config.lang_id,
			"type": 4
		}
		changeFields(this, params);
	});
	jQuery("#calc_data3_select").change(function(){
		params = {
			"action": "changeData3",
			"id": jQuery(this).val(),
			"langid": config.lang_id,
			"type": 5
		}
		changeFields(this, params);
	});
	jQuery("#calc_data4_select").change(function(){
		params = {
			"action": "changeData4",
			"id": jQuery(this).val(),
			"langid": config.lang_id,
			"type": 6
		}
		changeFields(this, params);
	});

	changeFields(jQuery("#calc_shipping_select"), {"action": "changeShipping","id":0,"langid": config.lang_id, "type": 0});
}

function updateFields(data, id, type)
{
	if (document.getElementById(id))
	{
	var a = document.getElementById('calc_shipping_table');
	if (id == 'calc_shipping_select')
	{
		if (data['data'].length > 1)
		{
			jQuery("#calc_shipping_div").css("display", "block");
			jQuery("#calc_vehicle_div").css("display", "block");
		} else {
			jQuery("#calc_shipping_div").css("display", "none");
		}
	}

	if (id == 'calc_vehicle_select')
	{
		if (data['data'].length > 1)
		{
			jQuery("#calc_vehicle_div").css("display", "block");
		} else if (document.getElementById('calc_shipping_div').style.display == 'none') {
			jQuery("#calc_vehicle_div").css("display", "none");
		}
	}

	if (config.maps.loaded)
	{
		ClearMarkers(type);
	}

	mapPoint[type] 	= new Array();
	Markers[type] 	= new Array();

	var i = 0;
	var opt = '';
	for(var key in data['data'])
	{
		opt += '<option value="' + data['data'][key]['id'] + '"' + ((data['data'][key]["default"] == 1) ? ' selected': '') + '>' + data['data'][key]['name'] + '</option>';
		if ((data['data'][key]['latitude']) && (data['data'][key]['longitude']) && (type > 1))
		{
			if ((config.maps.loaded) && (data['data'][key]['latitude'] != 0) && (data['data'][key]['longitude'] != 0))
			{
				mapPoint[type][i] = new Array();
				mapPoint[type][i]["pnt"] = new GLatLng(data['data'][key]['latitude'], data['data'][key]['longitude']);
				Markers[type][i] = new Object();
				Markers[type][i].marker = CreateMarker(data['data'][key]["id"], mapPoint[type][i]["pnt"], data['data'][key]["name"], type);
				config.maps.map.addOverlay(Markers[type][i].marker);
				Markers[type][i].marker.hide();
				i = i + 1;
			}
		}
	}

	jQuery('#' + id).html(opt);
	if (data['data'].length > 0)
	{
		jQuery('#' + id).removeAttr("disabled");
	}
	}
}

function generateResults(data)
{
	var result = "";
	for(var key in data)
	{
		var template = '<div class="mini_calc_label" style="line-height: 15px; font-weight: normal; padding-left: 0px;"><span style="position: relative; top: -5px;">'+data[key].message+'</span></div><table width="100%" border="0" cellpadding="0" cellspacing="0">'+
			'<tr>'+
			'	<td height="2" valign="top"><img class="iepngfix total_left_top" src="/images/total_left_top.png" border="0" alt=""></td>'+
			'	<td class="total_pixel" height="2"><img src="/images/spacer.gif" width="100%" height="2" border="0" alt=""></td>'+
			'	<td height="2" valign="top"><img class="iepngfix total_right_top" src="/images/total_right_top.png" border="0" alt=""></td>'+
			'</tr>'+
			'<tr>'+
			'	<td width="2" class="total_pixel"><img src="/images/spacer.gif" width="2" height="2" border="0" alt=""></td>'+
			'	<td width="100%" style="background-color: #FFFFFF;">'+
			'		<table border="0" cellpadding="0" cellspacing="0">'+
			'		<tr>'+
			'			<td style="vertical-align: top; width: 125px;"><img class="iepngfix" style="z-index: 100; position: absolute; margin-top: -6px; margin-left: -6px;" src="/images/arrow_3.png" width="132" height="44" border="0" alt=""><div style="z-index: 300; position: absolute; font-family: Arial; font-size: 25px; font-weight: bold; color: #FFFFFF; padding-left: 5px;"></div></td>'+
			'			<td style="font-family: Arial; font-size: 25px; font-weight: bold; color: #F0BA4D; padding-bottom: 1px;">$ '+data[key].price+'</td>'+
			'		</tr>'+
			'		</table>'+
			'	</td>'+
			'	<td width="2" class="total_pixel"><img src="/images/spacer.gif" width="2" height="2" border="0" alt=""></td>'+
			'</tr>'+
			'<tr>'+
			'	<td height="2" valign="top"><img class="iepngfix total_left_bottom" src="/images/total_left_bottom.png" border="0" alt=""></td>'+
			'	<td class="total_pixel" height="2"><img src="/images/spacer.gif" width="2" height="2" border="0" alt=""></td>'+
			'	<td height="2" valign="top"><img class="iepngfix total_right_bottom" src="/images/total_right_bottom.png" border="0" alt=""></td>'+
			'</tr>'+
			'</table>';

		result = result + template;
	}
	return result;
}

function changeFields(self, params)
{
	jQuery.ajax({
		url: '/AJAX/calc.php',
		data: params,
		type: 'post',
		dataType: 'json',
		params: params,
		success: function(data){

			if (this.params.type < 2)
			{
				jQuery('#calc_vehicle_select').attr("disabled", "disabled");
			}
			if (this.params.type < 3)
			{
				jQuery('#calc_data1_select').attr("disabled", "disabled");
			}
			if (this.params.type < 4)
			{
				jQuery('#calc_data2_select').attr("disabled", "disabled");
			}
			if (this.params.type < 5)
			{
				jQuery('#calc_data3_select').attr("disabled", "disabled");
			}
			if (this.params.type < 6)
			{
				jQuery('#calc_data4_select').attr("disabled", "disabled");
			}

			var fieldUpdated = false;
			var total = 0;
			var direct = new Array();
			var direct_inc = 0;
			for(var key in data)
			{
				if ((this.params.type == 6) && (data[5]['data'][0]['price'] != undefined) &&
					(data[5]['data'][0]['price'] > 0) && (key > 1))
				{
					total = total + parseFloat(data[key]['data'][0]['price']);
				}

					if (data[key]['data'][0]['price'] > 0)
					{
						direct[direct_inc] = new Object();
						if ((data[key - 1]['data'][0]['latitude'] != 0) && (data[key - 1]['data'][0]['longitude'] != 0) &&
							(data[key]['data'][0]['latitude'] != 0) && (data[key]['data'][0]['longitude'] != 0) &&
							(config.maps.loaded))
						{
							direct[direct_inc].fromLatLng = new GLatLng(data[key - 1]['data'][0]['latitude'], data[key - 1]['data'][0]['longitude']);
							direct[direct_inc].toLatLng = new GLatLng(data[key]['data'][0]['latitude'], data[key]['data'][0]['longitude']);
						}
						direct[direct_inc].fromName = data[key - 1]['data'][0]['name'];
						direct[direct_inc].fromCity = data[key - 1]['data'][0]['city'];
						direct[direct_inc].fromId = data[key - 1]['data'][0]['id'];
						direct[direct_inc].toName = data[key]['data'][0]['name'];
						direct[direct_inc].toCity = data[key]['data'][0]['city'];
						direct[direct_inc].toId = data[key]['data'][0]['id'];
						direct[direct_inc].type = parseInt(key) - 1;
						direct[direct_inc].price = parseFloat(data[key]['data'][0]['price']);
						direct[direct_inc].message = data[key - 1]['message'];
						direct_inc++;
					}

				var id = "";
				if ((key == 0) && (this.params.type < 1)) id = 'calc_shipping_select';
				if ((key == 1) && (this.params.type < 2)) id = 'calc_vehicle_select';
				if ((key == 2) && (this.params.type < 3)) id = 'calc_data1_select';
				if ((key == 3) && (this.params.type < 4)) id = 'calc_data2_select';
				if ((key == 4) && (this.params.type < 5)) id = 'calc_data3_select';
				if ((key == 5) && (this.params.type < 6)) id = 'calc_data4_select';
				if (id != "")
				{
					updateFields(data[key], id, this.params.type);
					fieldUpdated = true;
				}
			}

			if (config.maps.loaded)
			{
				clearDirections();
			}

			if (!config.showTotalOnly)
			{
				jQuery("#results").html(generateResults(direct));
			}

			if (config.maps.loaded)
			{
				setDirections(direct);
				if (total > 0)
				{
					zoomDirections();
				}
			}

			if (total > 0)
			{
				if (config.maps.loaded)
				{
					HideMarkers(data.length - 1);
				}
				jQuery("#total").find("#summ").html(total);
				jQuery("#total").show();
			} else {
				if (config.maps.loaded)
				{
					if (!fieldUpdated)
					{
						if (ShowMarkers(data.length - 1) == 2)
						{
							config.maps.map.setCenter(new GLatLng(data[0]['data'][0]['latitude'], data[0]['data'][0]['longitude']), parseInt(data[0]['data'][0]['zoom']));
						}
					} else {
						if (ShowMarkers(this.params.type) == 0)
						{
							config.maps.map.setCenter(new GLatLng(data[0]['data'][0]['latitude'], data[0]['data'][0]['longitude']), parseInt(data[0]['data'][0]['zoom']));
						}
					}
				}
				jQuery("#total").hide();
			}

			if ((fieldUpdated) && (id != ""))
			{
				jQuery('#' + id).change();
			}
		},
		complete: function(xhr){
		},
		error: function(xhr, status){
		}
	});
}





