var googlemaps = new Array();
googlemaps['id'] = '';
googlemaps['key'] = '';
googlemaps['loc'] = '';
googlemaps['lang'] = '';
googlemaps['core'] = '';
googlemaps['images'] = '';
googlemaps['domain'] = '';
googlemaps['texts'] = new Array();
googlemaps['domains'] = new Array();
googlemaps['locations'] = new Array();
googlemaps['markers'] = new Array();
googlemaps['markerspath'] = '';
googlemaps['areasedit'] = false;
googlemaps['areas'] = new Array();

var map;
var gdir;
var geocoder = null;
var addressMarker;
var gtimeout;
var gelem;
var gerror;
var gtime = new Date();
var gdebug = false;
var gerror = new Array();
var gmarkers = false;

function googlemaps_build() {
	// ------------------------------------------------------------------------------
	// ERROR ID
		var id = googlemaps['id'];
	// ------------------------------------------------------------------------------
	// CORE
		if(GBrowserIsCompatible()) {
			if(gmarkers) {
				var arraykey = 'markers';
			} else {
				var arraykey = 'locations';
			}
			map = new GMap2(document.getElementById(googlemaps['id']));
			gdir = new GDirections(map, document.getElementById('googlemaps_directions'));
			GEvent.addListener(gdir, 'load', googlemaps_onloaddirections);
			GEvent.addListener(gdir, 'error', googlemaps_onloaddirectionserror);
			geocoder = new GClientGeocoder();
			map.setCenter(new GLatLng(googlemaps[arraykey][googlemaps['loc']].latitude, googlemaps[arraykey][googlemaps['loc']].longitude), googlemaps[arraykey][googlemaps['loc']].zoom);
			googlemaps_nobrand();
			for(var i in googlemaps[arraykey]) {
				if(googlemaps[arraykey][i].longitude == 0 && googlemaps[arraykey][i].latitude == 0) {
					geocoder.getLocations(googlemaps[arraykey][i].adres[googlemaps['lang']], function(point) {
						if(point.Status.code == 602) {
							//alert(point.name + ' - ' + point.Status.code + ' - ');
						}
						//alert(point.name + ' - ' + point.Placemark[0].Point.coordinates[0]);
						var gi = '';
						for(var i in googlemaps[arraykey]) {
							if(googlemaps[arraykey][i].latitude == 0 && googlemaps[arraykey][i].longitude == 0) {
								if(googlemaps[arraykey][i].adres[googlemaps['lang']].toLowerCase() == point.name.toLowerCase() && gi == '') {
									//alert(i);
									googlemaps[arraykey][i].latitude = point.Placemark[0].Point.coordinates[1];
									googlemaps[arraykey][i].longitude = point.Placemark[0].Point.coordinates[0];
									// AJAX POST ID + LAT + LON
									var httpconnect = createHTTPHandler();
									httpconnect.open('GET', googlemaps['markerspath'] + '?id=' + googlemaps[arraykey][i].id + '&lat=' + googlemaps[arraykey][i].latitude + '&lon=' + googlemaps[arraykey][i].longitude, false);
									httpconnect.send(null);
									// ----------
									gi = i;
								}
							}
						}
						//alert(gi);
						var icon = new GIcon();
						if(googlemaps[arraykey][gi].description) {
							icon.description = googlemaps[arraykey][gi].description;
						}
						if(googlemaps[arraykey][gi].id) {
							icon.id = googlemaps[arraykey][gi].id;
						}
						icon.image = googlemaps['images'] + googlemaps[arraykey][gi].marker_source;
						icon.iconSize = new GSize(googlemaps[arraykey][gi].marker_width, googlemaps[arraykey][gi].marker_height);
						icon.iconAnchor = new GPoint(googlemaps[arraykey][gi].marker_x, googlemaps[arraykey][gi].marker_y);
						var marker = new GMarker(new GLatLng(googlemaps[arraykey][gi].latitude, googlemaps[arraykey][gi].longitude), icon);
						if(gmarkers) {
							if(typeof googlemaps_custom_marker == 'function') {
								googlemaps_custom_marker(marker);
							}
						} else {
							if(typeof googlemaps_custom_location == 'function') {
								googlemaps_custom_location(marker);
							} else {
								if(typeof googlemaps_custom_marker == 'function') {
									googlemaps_custom_marker(marker);
								}
							}
						}
						map.addOverlay(marker);
					});
				} else {
					var icon = new GIcon();
					if(googlemaps[arraykey][i].description) {
						icon.description = googlemaps[arraykey][i].description;
					}
					if(googlemaps[arraykey][i].id) {
						icon.id = googlemaps[arraykey][i].id;
					}
					icon.image = googlemaps['images'] + googlemaps[arraykey][i].marker_source;
					icon.iconSize = new GSize(googlemaps[arraykey][i].marker_width, googlemaps[arraykey][i].marker_height);
					icon.iconAnchor = new GPoint(googlemaps[arraykey][i].marker_x, googlemaps[arraykey][i].marker_y);
					var marker = new GMarker(new GLatLng(googlemaps[arraykey][i].latitude, googlemaps[arraykey][i].longitude), icon);
					if(gmarkers) {
						if(typeof googlemaps_custom_marker == 'function') {
							googlemaps_custom_marker(marker);
						}
					} else {
						if(typeof googlemaps_custom_location == 'function') {
							googlemaps_custom_location(marker);
						} else {
							if(typeof googlemaps_custom_marker == 'function') {
								googlemaps_custom_marker(marker);
							}
						}
					}
					map.addOverlay(marker);
				}
				var option = document.createElement('option');
				var name = document.createTextNode(googlemaps[arraykey][i].name[googlemaps['lang']]);
				option.setAttribute('value', i);
				if(i == googlemaps['loc']) {
					option.setAttribute('selected', 'selected');
				}
				option.appendChild(name);
				gelem = document.getElementById('googlemaps_tolocation');
				if(gelem) {
					gelem.appendChild(option);
				}
			}
			// FUNCTION
			if(typeof googlemaps_custom_build == 'function') {
				googlemaps_custom_build(map);
			} else {
				googlemaps_error(id, 'Missing function: "googlemaps_custom_build"');
			}
			// FUNCTION
			if(typeof googlemaps_custom_marker == 'function') {
			} else {
				googlemaps_error(id, 'Missing function: "googlemaps_custom_marker"');
			}
			// FUNCTION
			if(typeof googlemaps_custom_location == 'function') {
			} else {
				googlemaps_error(id, 'Missing function: "googlemaps_custom_location"');
			}
			// FUNCTION
			if(typeof googlemaps_custom_submit == 'function') {
			} else {
				googlemaps_error(id, 'Missing function: "googlemaps_custom_submit"');
			}
			// ELEMENT
			gelem = document.getElementById('googlemaps_locale');
			if(gelem) {
				gelem.value = googlemaps['lang'];
			} else {
				googlemaps_error(id, 'Missing element: "googlemaps_locale"', 1);
			}
			// ELEMENT
			gelem = document.getElementById('googlemaps_adres');
			if(gelem) {
				gelem.innerHTML = googlemaps['texts'].adres;
			} else {
				googlemaps_error(id, 'Missing element: "googlemaps_adres"');
			}
			// ELEMENT
			gelem = document.getElementById('googlemaps_printtext');
			if(gelem) {
				gelem.innerHTML = googlemaps['texts'].printer;
			} else {
				googlemaps_error(id, 'Missing element: "googlemaps_printtext"');
			}
			// ELEMENT
			gelem = document.getElementById('googlemaps_print');
			if(gelem) {
				gelem.style.visibility = 'hidden';
			} else {
				googlemaps_error(id, 'Missing element: "googlemaps_print"');
			}
			// ELEMENT
			gelem = document.getElementById('googlemaps_toadres');
			if(gelem) {
				gelem.innerHTML = googlemaps['texts'].toadres;
			} else {
				googlemaps_error(id, 'Missing element: "googlemaps_toadres"');
			}
			// ELEMENT
			gelem = document.getElementById('googlemaps_button');
			if(gelem) {
				gelem.value = googlemaps['texts'].button;
			} else {
				googlemaps_error(id, 'Missing element: "googlemaps_button"', 1);
			}
			// ELEMENT
			gelem = document.getElementById('googlemaps_form');
			if(gelem) {
				gelem.onsubmit = function() {
					googlemaps_submit();
					return false;
				}
			} else {
				googlemaps_error(id, 'Missing element: "googlemaps_form"', 1);
			}
			// ELEMENT
			gelem = document.getElementById('googlemaps_input');
			if(gelem) {
				gelem.value = googlemaps['texts'].input;
				gelem.onfocus = function() {
					googlemaps_focus();
				}
				gelem.onblur = function() {
					googlemaps_blur();
				}
			} else {
				googlemaps_error(id, 'Missing element: "googlemaps_input"', 1);
			}
			// ELEMENT
			gelem = document.getElementById('googlemaps_tolocation');
			if(gelem) {
				gelem.onchange = function() {
					googlemaps_changeloc();
				}
			} else {
				googlemaps_error(id, 'Missing element: "googlemaps_tolocation"', 1);
			}
		} else {
			googlemaps_error(id, 'Browser not supported!', 0);
		}
		googlemaps_debug(id);
	// ------------------------------------------------------------------------------
}

function googlemaps_include(siteurl, coreurl, lang, id, imagepath, markerspath) {
	// ------------------------------------------------------------------------------
	// ERROR VAR
		gerror[id] = '';
	// ------------------------------------------------------------------------------
	// DEFAULT ARGUMENT VALUES
		markerspath = typeof(markerspath) != 'undefined' ? markerspath : false;
	// ------------------------------------------------------------------------------
	// CORE
		gelem = document.getElementById(id);
		if(gelem) {
			googlemaps['id'] = id;
			googlemaps['key'] = googlemaps['domains'][siteurl].key;
			googlemaps['loc'] = googlemaps['domains'][siteurl].loc;
			if(document.location.hash) {
				var lochash = document.location.hash;
				lochash = lochash.replace(/#/, '');
				if(googlemaps['locations'][lochash]) {
					googlemaps['loc'] = lochash;
				}
			}
			googlemaps['lang'] = lang;
			googlemaps['core'] = coreurl;
			googlemaps['images'] = siteurl + '/' + imagepath;
			googlemaps['domain'] = siteurl;
			var protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
			document.write(unescape("%3Cscript src='" + protocol + "maps.google.com/maps?file=api&v=2&key=" + googlemaps['key'] + "' type='text/javascript'%3E%3C/script%3E"));
			if(markerspath) {
				gmarkers = true;
				markerspath = siteurl + '/' + markerspath;
				var randomnumber = Math.floor(Math.random() * 999999);
				var randomarray = markerspath.split('?');
				if(randomarray.length == 1) {
					var randomloader = '?gmaprandomload=' + randomnumber;
				} else {
					var randomloader = '&gmaprandomload=' + randomnumber;
				}
				googlemaps['markerspath'] = markerspath;
				document.write(unescape("%3Cscript src='" + markerspath + randomloader + "' type='text/javascript'%3E%3C/script%3E"));
			}
			googlemaps_addonload();
		} else {
			googlemaps_error(id, 'Missing element: "'+id+'"');
			googlemaps_debug(id);
		}
	// ------------------------------------------------------------------------------
}

function googlemaps_addonload() {    
	if(window.addEventListener) {
		window.addEventListener('load', googlemaps_build, false);
		window.addEventListener('beforeprint', googlemaps_skin, false);
	} else if(window.attachEvent) {
		window.attachEvent('onload', googlemaps_build);
		window.attachEvent('onbeforeprint', googlemaps_skin);
	}
}

function googlemaps_submit() {
	if(typeof googlemaps_custom_submit == 'function') {
		googlemaps_custom_submit();
	}
	var status = googlemaps_setroute();
	var logroute = googlemaps_logroute();
}

function googlemaps_setroute() {
	var getadres = document.getElementById('googlemaps_input').value;
	var alertempty = googlemaps['texts'].empty;
	if(getadres == '') {
		alert(alertempty);
	} else if(getadres == googlemaps['texts'].input) {
		alert(alertempty);
	} else {
		geocoder.getLocations(getadres, googlemaps_response);
	}
}

function googlemaps_response(response) {
	if (!response || response.Status.code != 200) {
	} else {
		place = response.Placemark[0];
		adres = place.address + ' ' + place.AddressDetails.Country.CountryNameCode;
		var location = googlemaps['locations'][googlemaps['loc']].adres[googlemaps['lang']];
		googlemaps_directions(place.address, location, document.getElementById('googlemaps_locale').value);
		document.getElementById('googlemaps_print').style.visibility = 'visible';
		return false;
	}
}

function googlemaps_directions(fromaddress, toaddress, locale) {
	document.getElementById('googlemaps_directions').innerHTML = '';
	gdir.load("from: " + fromaddress + " to: " + toaddress, { "locale": locale });
}

function googlemaps_logroute() {
	var getadres = document.getElementById('googlemaps_input').value;
	var httpconnect = createHTTPHandler();
	httpconnect.open('POST', googlemaps['core'] + '/include/googlemaps/logroute.ajax.php?address=' + getadres + '&siteurl=' + googlemaps['domain'], false);
	httpconnect.send(null);
	return false;
}

function googlemaps_focus() {
	var value = document.getElementById('googlemaps_input').value;
	if(value == googlemaps['texts'].input) {
		value = '';
	}
	document.getElementById('googlemaps_input').value = value;
}

function googlemaps_blur() {
	var value = document.getElementById('googlemaps_input').value;
	if(value == '') {
		value = googlemaps['texts'].input;
	}
	document.getElementById('googlemaps_input').value = value;
}

function googlemaps_changeloc() {
	var selected = document.getElementById('googlemaps_tolocation').selectedIndex;
	var location = document.getElementById('googlemaps_tolocation').getElementsByTagName('option')[selected].value;
	map.setCenter(new GLatLng(googlemaps['locations'][location].latitude, googlemaps['locations'][location].longitude), googlemaps['locations'][location].zoom);
	var getadres = document.getElementById('googlemaps_input').value;
	if(getadres == '') {
	} else if(getadres == googlemaps['texts'].input) {
	} else {
		googlemaps_submit();
	}
}

function googlemaps_onloaddirections() {
	if(gdir.getStatus().code == 200) {
		gtimeout = window.setTimeout(googlemaps_skin, 20);
	}
}

function googlemaps_onloaddirectionserror() {
	/*if (gdir.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: " + gdir.getStatus().code);
	else if (gdir.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: " + gdir.getStatus().code);
	else if (gdir.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: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)
		alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.n Error code: " + gdir.getStatus().code);
	else if (gdir.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: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.n Error code: " + gdir.getStatus().code);
	else alert("An unknown error occurred.");*/
}

function googlemaps_polygon_coordinates_return(object) {
	var vertexcount = object.getVertexCount();
	var coordinates = '';
	for(i=0; i<vertexcount; i++) {
		var vertex = object.getVertex(i);
		vertex = vertex.toString();
		//vertex = vertex.replace(', ', ',');
		coordinates = coordinates + vertex;
	}
	return coordinates;
}

function googlemaps_polygon_center_return(object) {
	var center = new Object();
	var string = object.getBounds();
	string = string.toString();
	var arrays = string.split(',');
	arrays[0] = arrays[0].toString();
	arrays[0] = arrays[0].replace('(', '');
	arrays[0] = arrays[0].replace('(', '');
	arrays[0] = arrays[0].replace(')', '');
	arrays[0] = arrays[0].replace(')', '');
	arrays[0] = arrays[0].replace(',', '');
	arrays[0] = parseFloat(arrays[0]);
	arrays[1] = arrays[1].toString();
	arrays[1] = arrays[1].replace('(', '');
	arrays[1] = arrays[1].replace('(', '');
	arrays[1] = arrays[1].replace(')', '');
	arrays[1] = arrays[1].replace(')', '');
	arrays[1] = arrays[1].replace(',', '');
	arrays[1] = parseFloat(arrays[1]);
	arrays[2] = arrays[2].toString();
	arrays[2] = arrays[2].replace('(', '');
	arrays[2] = arrays[2].replace('(', '');
	arrays[2] = arrays[2].replace(')', '');
	arrays[2] = arrays[2].replace(')', '');
	arrays[2] = arrays[2].replace(',', '');
	arrays[2] = parseFloat(arrays[2]);
	arrays[3] = arrays[3].toString();
	arrays[3] = arrays[3].replace('(', '');
	arrays[3] = arrays[3].replace('(', '');
	arrays[3] = arrays[3].replace(')', '');
	arrays[3] = arrays[3].replace(')', '');
	arrays[3] = arrays[3].replace(',', '');
	arrays[3] = parseFloat(arrays[3]);
	center.latitude = (arrays[0] + arrays[2]) / 2;
	center.longitude = (arrays[1] + arrays[3]) / 2;
	return center;
}

function googlemaps_skin() {
	if(document.getElementById('googlemaps_directions')) {
		if(document.getElementById('googlemaps_directions').innerHTML == '') {
			var gtimeout = window.setTimeout(googlemaps_skin, 20);
		} else {
			var countelem = 0;
			var elements = document.getElementById('googlemaps_directions').getElementsByTagName('table');
			elements[0].style.backgroundColor = googlemaps['locations'][googlemaps['loc']].directions_bg;
			elements[0].style.border = '1px solid ' + googlemaps['locations'][googlemaps['loc']].directions_border;
			elements[0].getElementsByTagName('img')[0].src = googlemaps['images'] + '' + googlemaps['locations'][googlemaps['loc']].marker_a;
			elements[elements.length - 2].style.backgroundColor = googlemaps['locations'][googlemaps['loc']].directions_bg;
			elements[elements.length - 2].style.border = '1px solid ' + googlemaps['locations'][googlemaps['loc']].directions_border;
			elements[elements.length - 2].getElementsByTagName('img')[0].src = googlemaps['images'] + '' + googlemaps['locations'][googlemaps['loc']].marker_b;
			for(i = 0; i < document.getElementById(googlemaps['id']).getElementsByTagName('img').length; i++) {
				var source = document.getElementById(googlemaps['id']).getElementsByTagName('img')[i].src;
				source = source.substring(source.lastIndexOf('/') + 1, source.length);
				if(source == 'marker_greenA.png' || source == 'marker_greenAie.gif') {
					document.getElementById(googlemaps['id']).getElementsByTagName('img')[i].src = googlemaps['images'] + '' + googlemaps['locations'][googlemaps['loc']].marker_a;
					countelem++;
				}
				if(source == 'marker_greenB.png' || source == 'marker_greenBie.gif') {
					document.getElementById(googlemaps['id']).getElementsByTagName('img')[i].src = googlemaps['images'] + '' + googlemaps['locations'][googlemaps['loc']].marker_b;
					countelem++;
				}
			}
			if(countelem < 2) {
				var gtimeout = window.setTimeout(googlemaps_skin, 20);
			}
			googlemaps_nobrand();
		}
	}
}

function googlemaps_nobrand() {
	/*if(document.getElementById(googlemaps['id']).innerHTML == '') {
		var gtimeout = window.setTimeout(googlemaps_nobrand, 20);
	} else {
		var countelem = 0;
		for(i = 0; i < document.getElementById(googlemaps['id']).getElementsByTagName('div').length; i++) {
			var divselect = document.getElementById(googlemaps['id']).getElementsByTagName('div')[i];
			if(divselect.style.bottom == '2px' && divselect.getAttribute('id') == 'logocontrol') {
				divselect.style.display = 'none';
				divselect.style.height = '0px';
				divselect.style.width = '0px';
				divselect.style.overflow = 'hidden';
				countelem++;
			}
			if(divselect.style.bottom == '2px' && divselect.style.right == '3px') {
				divselect.style.display = 'none';
				divselect.style.height = '0px';
				divselect.style.width = '0px';
				divselect.style.overflow = 'hidden';
				countelem++;
			}
		}
		if(countelem < 2) {
			var gtimeout = window.setTimeout(googlemaps_nobrand, 20);
		}
	}*/
}

function googlemaps_showtooltip(marker) {
	if(document.getElementById(googlemaps['id'])) {
		if(document.getElementById('googlemaps_tooltip_wrapper')) {
		} else {
			var tooltip = document.createElement('div');
			tooltip.id = 'googlemaps_tooltip_wrapper';
			document.getElementById(googlemaps['id']).appendChild(tooltip);
		}
		marker.tooltip = '<div class="googlemaps_tooltip">'+marker.description+'<\/div>';
		document.getElementById('googlemaps_tooltip_wrapper').innerHTML = marker.tooltip;
		var point = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
		var offset = map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
		var anchor = marker.getIcon().iconAnchor;
		var width = marker.getIcon().iconSize.width;
		var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y)); 
		pos.apply(tooltip);
	}
}

function googlemaps_hidetooltip(marker) {
	if(document.getElementById(googlemaps['id'])) {
		if(document.getElementById('googlemaps_tooltip_wrapper')) {
			document.getElementById(googlemaps['id']).removeChild(document.getElementById('googlemaps_tooltip_wrapper'));
		}
	}
}

function googlemaps_error(id, value, level) {
	// ------------------------------------------------------------------------------
	// LEVELS
	// 0 = Fatal
	// 1 = Warning
	// 2 = Notice
	// ------------------------------------------------------------------------------
	// DEFAULT ARGUMENT VALUES
		level = typeof(level) != 'undefined' ? level : 2;
	// ------------------------------------------------------------------------------
	// CORE
		gerror[id] = gerror[id] + level + ' - ' + value + "\n";
	// ------------------------------------------------------------------------------
}

function googlemaps_debug(id) {
	// ------------------------------------------------------------------------------
	// CORE
		if(gdebug) {
			if(gerror[id] == '') {
				gerror[id] = 'No errors occurred!' + "\n\n" + 'Date:' + "\n" + gtime;
			} else {
				gerror[id] = gerror[id] + "\n" + 'Date:' + "\n" + gtime;
			}
			gerror[id] = 'Debug:' + "\n" + 'googlemaps_include("' + id + '")' + "\n\n" + 'Log:' + "\n" + gerror[id] + "\n\n" + 'Errors:' + "\n" + '0 - Fatal' + "\n" + '1 - Warning' + "\n" + '2 - Notice';
			alert(gerror[id]);
		}
	// ------------------------------------------------------------------------------
}
