var SubcatUpdate = function () {
    this.form = document.getElementById('tradeSearch');
	if (this.form) {
		this.baseUrl = 'getsubcats-%%.html';
		eventHandler.addEvent(this.form.elements.cat, 'change', function () {
			this.init(this.handleResponse.bindTo(this));
			var cat = this.form.elements.cat.options[this.form.elements.cat.selectedIndex].value;
			this.load(this.baseUrl.replace(/%%/, cat));
		}.bindTo(this));
	}
};
SubcatUpdate.prototype = new HttpRequest();

SubcatUpdate.prototype.handleResponse = function (response) {
	try {
		response = JSON.parse(response);
		if (typeof response == 'object') {
			throw true;
		} else {
			throw false;
		}
	} catch (e) {
		if (e !== true) {
			return;
		} else {
			this.setOptions(response);
		}
	}
};
SubcatUpdate.prototype.setOptions = function (options) {
	var option;
	this.form.elements.subCat.options.length=1;
	for (var i in options) {
		option = new Option(options[i], i, false, false);
		this.form.elements.subCat.options[this.form.elements.subCat.options.length] = option;
	}
};

var map;
var gdir;
var GoogleMaps = function () {};
GoogleMaps.prototype.cc = 'AT';
GoogleMaps.prototype.atc = {'lat':47.487513008956554,'lon':13.787841796875}; // startpunkt von at
GoogleMaps.prototype.load = function () {
	var point;
	this.container = document.getElementById("map");
	if (this.container && GBrowserIsCompatible()){
		map = new GMap2(document.getElementById("map"));
		GEvent.addListener(map, "load", function() {
			document.getElementById("preloader").style.display = "none";
		}.bindTo(this));
		map.addControl(new GLargeMapControl());
		var mapControl = new GMapTypeControl();
		map.addControl(mapControl);

		if(this.mapStart == 1) {  // startmap anzeigen zentriert ueber at
			map.setCenter(new GLatLng(this.atc.lat,this.atc.lon), 7);
		}

		if(this.mapStart == 2 || this.mapStart == 3){ // eine stadt wurde ueber die top 30 staedte gewaehlt oder ueber die suche wurde eine adresse gesucht
			if (typeof this.lat != 'undefined') { // Koordinaten verwenden
				point = new GLatLng(this.lat,this.lon);
				this.showCity.call(this, point);
			} else {
			this.geocoder = new GClientGeocoder();
				if (this.geocoder) {
					this.geocoder.setBaseCountryCode(this.cc);
					this.geocoder.getLatLng ( // erster Versuch Adresse zu Geokodieren
						this.address,
						function (point) {
							if (point) {
								this.showCity.call(this, point);
							} else if (this.shortAddress != '') {
								this.geocoder.getLatLng ( // zweiter Versuch mit gekürzter Adresse
									this.shortAddress,
									function (point) {
										if (!point) { // Nix gefunden, setze Default
											this.mapZoom = 6;
											point = new GLatLng(this.atc.lat,this.atc.lon);
										}
										this.showCity.call(this, point);
									}.bindTo(this)
								);
							}
						}.bindTo(this)
					);
				}
			}
		}

		if(this.mapStart == 4){ // routenplaner
			this.setDirections(this.routeFrom, this.routeTo, 'de');
		}

		if (this.mapStart == 5) { // Gewerbesuche Suchergebnisse anzeigen
			var searchResultElements = renderer.getElements('.searchResult', document.getElementById('searchResultsContainer'));
			this.geocoder = new GClientGeocoder();
			this.sw = {"y":360,"x":360};
			this.ne = {"y":0,"x":0};
			if (this.geocoder && this.searchResults.length > 0) {
				var i=0;
				this.searchResultsInterval = window.setInterval(function () {
					this.geocoder.setBaseCountryCode(this.cc);
					var address='';
					if (this.searchResults[i].street != '' && this.searchResults[i].zip != '' && this.searchResults[i].city != '') {
						address = this.searchResults[i].street+', '+this.cc+'-'+this.searchResults[i].zip+' '+this.searchResults[i].city;
					}
					if (this.searchResults[i].street == '' && this.searchResults[i].zip != '' && this.searchResults[i].city != '') {
						address = this.cc+'-'+this.searchResults[i].zip+' '+this.searchResults[i].city;
					}
					if (this.searchResults[i].street == '' && this.searchResults[i].zip == '' && this.searchResults[i].city != '') {
						address = this.cc+'-'+this.searchResults[i].city;
					}
					if (this.searchResults[i].street == '' && this.searchResults[i].zip != '' && this.searchResults[i].city == '') {
						address = this.cc+'-'+this.searchResults[i].zip;
					}
					this.geocoder.getLatLng (
						address,
						function (point, n) {
							this.sw.y = Math.min(this.sw.y, point.y);
							this.sw.x = Math.min(this.sw.x, point.x);
							this.ne.y = Math.max(this.ne.y, point.y);
							this.ne.x = Math.max(this.ne.x, point.x);
							this.searchResults[n].point = point;
							this.searchResults[n].container = searchResultElements[n];
							this.searchResults[n].index = n;
							if (n>=this.searchResults.length-1) {
								this.bounds = new GLatLngBounds(new GLatLng(this.sw.y, this.sw.x), new GLatLng(this.ne.y, this.ne.x));
								this.boundsToMap();
								this.displayLocations();
							}
						}.bindTo(this, i)
					);
					i++;
					if (i>=this.searchResults.length) {
						window.clearInterval(this.searchResultsInterval);
					}
				}.bindTo(this), 350);
			}
		}
		map.addControl(new google.maps.LocalSearch(), new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,20)));
	}
};
GoogleMaps.prototype.showCity = function (point) {
	var marker, icon, color;
	icon = new GIcon();
	color = this.icons.shift();
	icon.image = 'images/icons/pointer/'+color+'.png';
	this.icons.push(color);
	icon.shadow = 'images/icons/pointer/shadow.png';
	icon.transparent = 'images/icons/pointer/transparent.png';
	icon.iconSize = new GSize(22, 22);
	icon.shadowSize = new GSize(22, 22);
	icon.iconAnchor = new GPoint(2, 22);
	icon.infoWindowAnchor = new GPoint(12, 0);
	marker = new GMarker(point, {"icon":icon});
	//console.log(point.Nd+' '+point.Ga);
	map.setCenter(point, this.mapZoom);
	map.addOverlay(marker);
};
GoogleMaps.prototype.boundsToMap = function () {
	map.setCenter(this.bounds.getCenter(), map.getBoundsZoomLevel(this.bounds)-1);
};
GoogleMaps.prototype.displayLocations = function () {
	for (var i=0;i<this.searchResults.length;i++) {
		this.createMarker({"index":i,"type":"searchResult"});
	}
};
GoogleMaps.prototype.onGDirectionsLoad = function () {
	// Use this function to access information about the latest load()
	// results.

	// e.g.
	// document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	// and yada yada yada...
	return;
};
GoogleMaps.prototype.setDirections = function (fromAddress, toAddress, locale) {
	if (typeof this.gdir != 'undefined') {
		this.gdir.clear();
	} else {
		this.gdir = new GDirections(map, document.getElementById("directions"));
	}
	GEvent.addListener(this.gdir, "load", this.onGDirectionsLoad.bindTo(this));
	GEvent.addListener(this.gdir, "error", this.handleErrors.bindTo(this));
	if(fromAddress=="") {
		alert("Bitte geben Sie eine Startadresse ein");
		return;
	} else {
		document.getElementById("map").style.display = "block";
		this.gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
	}
};

GoogleMaps.prototype.handleErrors = function () {
	if (this.gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("Mindestens eine Adresse konnte nicht gefunden werden. Entweder die Adresse ist sehr neu, nicht eindeutig oder sie ist falsch. Versuchen Sie es mir der Angabe Stadt, PLZ erneut.\nError code: " + this.gdir.getStatus().code);
	else if (this.gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("Auf Grund eines unbekannten Adress-Fehlers konnte die Rote nicht berechnet werden.\n Error code: " + this.gdir.getStatus().code);
	else if (this.gdir.getStatus().code == G_GEO_MISSING_QUERY)
		alert("Bitte geben Sie eine gültige Adresse an.\n Error code: " + this.gdir.getStatus().code);
// else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//  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 (this.gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("Zur Zeit kann Ihre Route leider nicht berechnet werden. \n Error code: " + this.gdir.getStatus().code);
	else if (this.gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("Eine Adresse konnte leider nicht ermittelt werden.\n Error code: " + this.gdir.getStatus().code);
	else alert("Ein unbekannter Fehler ist aufgetreten.");

	map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl());
	var mapControl = new GMapTypeControl();
	map.addControl(mapControl);
	map.setCenter(new GLatLng(this.atc.lat,this.atc.lon), 6);
};
/**
 * Create a Marker for the Map
 *
 * @param options 	{object}		Markeroptions (READ Code)
 */
GoogleMaps.prototype.createMarker = function (options) {
	var type=null, i=0;
	if (options) {
		if (typeof options.type != 'undefined') {
			type = options.type;
		}
		if (typeof options.index != 'undefined') {
			i = options.index;
		}
	}
	switch (type) {
		case 'searchResult':
			this.searchResults[i].icon = new GIcon();
			this.searchResults[i].color = this.icons.shift();
			this.searchResults[i].icon.image = 'images/icons/pointer/'+this.searchResults[i].color+'.png';
			this.icons.push(this.searchResults[i].color);
			this.searchResults[i].icon.shadow = 'images/icons/pointer/shadow.png';
			this.searchResults[i].icon.transparent = 'images/icons/pointer/transparent.png';
			this.searchResults[i].icon.iconSize = new GSize(22, 22);
			this.searchResults[i].icon.shadowSize = new GSize(22, 22);
			this.searchResults[i].icon.iconAnchor = new GPoint(2, 22);
			this.searchResults[i].icon.infoWindowAnchor = new GPoint(12, 0);
			this.searchResults[i].marker = new GMarker(this.searchResults[i].point, {"icon":this.searchResults[i].icon});
			GEvent.addListener(this.searchResults[i].marker, "mouseover", function(n) {
				return function () {
					this.searchResults[n].container.style.borderColor = 'black';
					this.searchResults[n].container.getElementsByTagName('a')[0].style.backgroundImage = 'url(images/icons/marker/'+this.searchResults[n].color+'.png)';
				}.bindTo(this);
			}.call(this, i));
			GEvent.addListener(this.searchResults[i].marker, "mouseout", function(n) {
				return function () {
					this.searchResults[n].container.style.borderColor = '';
					this.searchResults[n].container.getElementsByTagName('a')[0].style.backgroundImage = '';
				}.bindTo(this);
			}.call(this, i));
			GEvent.addListener(this.searchResults[i].marker, "click", function(n) {
				return function () {
					this.searchResults[n].marker.openInfoWindowHtml('<strong>'+this.searchResults[n].name+'</strong><br />'+this.searchResults[n].street+'<br />'+this.searchResults[n].zip+' '+this.searchResults[n].city);
				}.bindTo(this);
			}.call(this, i));
			map.addOverlay(this.searchResults[i].marker);
			this.signal = renderer.createElement('img', {
				"src":"images/icons/pointer/signal.gif",
				"style":{
					"position":"absolute",
					"top":0,
					"left":0
				}
			});
			eventHandler.addEvent(this.searchResults[i].container.getElementsByTagName('a')[0], 'mouseover', function (n) {
				return function () {
					var offset = map.fromLatLngToContainerPixel(this.searchResults[n].point);
					this.signal.style.left = (offset.x-6) + 'px';
					this.signal.style.top = (offset.y-28) + 'px';
					this.signal.renderIn(this.container);
				}.bindTo(this);
			}.call(this, i));
			eventHandler.addEvent(this.searchResults[i].container.getElementsByTagName('a')[0], 'mouseout', function (n) {
				return function () {
					if (this.signal.parentNode != null) {
						this.signal.remove();
					}
				}.bindTo(this);
			}.call(this, i));
			break;
		case 'route':
			break;
	}
};

// marker mit unterschiedlichen buchstaben fuer die objekte in der umgebung von hotels
function createMarker(point, index, myName) {
	// Create a base icon for all of our markers that specifies the
	// shadow, icon dimensions, etc.
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(20, 34);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);

	// Create a lettered icon for this point using our icon class
	var letter = String.fromCharCode("A".charCodeAt(0) + index);
	var letteredIcon = new GIcon(baseIcon);
	letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";

	// Set up our GMarkerOptions object
	markerOptions = { icon:letteredIcon };
	var marker = new GMarker(point, markerOptions);

	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(myName);
	});
	return marker;
}

/*
Bildtauscher
*/
var counter = new Array();
counter["hotelBild"]=0;
var bildI = '';
function bildtausch (wert,bild,vor,zurueck){
	if (bild=="hotelBild"){
		bildI=counter[bild];
	}
	if (wert=="zurueck"){
		if (bildI>0){
			bildI--;
			document.getElementById(bild).src = bildnamen[bildI];
		}
	}
	if (wert=="vor"){
		if ((bildI+1)<bildnamen.length){
			bildI++;
			document.getElementById(bild).src = bildnamen[bildI];
		}
	}
	if (bildI==0){
		document.getElementById(zurueck).src = "images/1px_hellgrau.gif";
		document.getElementById(zurueck).style.cursor = "default";
		document.getElementById('lupe').style.display = "none";
	}else{
		document.getElementById(zurueck).src = "images/img_pfeil_zurueck.gif";
		document.getElementById(zurueck).style.cursor = "pointer";
	}
	if ((bildI+1)<bildnamen.length){
		document.getElementById(vor).src = "images/img_pfeil_vor.gif";
		document.getElementById(vor).style.cursor = "pointer";
	}else{
		document.getElementById(vor).src = "images/1px_hellgrau.gif";
		document.getElementById(vor).style.cursor = "default";
	}
	if(bildI>0){
		document.getElementById('lupe').style.display = "block";
	}
	counter[bild]=bildI;
}

/*bild vergroessern*/
function bildLupe(mySrc){
	document.getElementById('hotelBildGross').style.display = "block";
	document.getElementById('bildGross').src = mySrc;
}


eventHandler.addLoadEvent(function () {
	for (var i in gmOptions) {
		GoogleMaps.prototype[i] = gmOptions[i];
	}
	if (document.getElementById('resultBrowser')) {
		r = new ResultBrowserHelper();
        r.init(document.getElementById('resultBrowser'));
	}
	GoogleMaps = new GoogleMaps();
	GoogleMaps.load();
    this.subcatUpdate = new SubcatUpdate();
	if (this.subcatUpdate.form) {
		//var resetButton = this.subcatUpdate.form.elements[this.subcatUpdate.form.elements.length-1];
		eventHandler.addEvent(document.getElementById('tradeSearchReset'), 'click', function () {
			for (var i in this.elements) {
				if (typeof this.elements[i].tagName != 'undefined' &&
					this.elements[i].tagName == 'SELECT'
				) {
					var attr = this.elements[i].options[this.elements[i].selectedIndex].getAttributeNode('selected');
					if (attr) {
						this.elements[i].options[this.elements[i].selectedIndex].removeAttributeNode(attr);
					}
					this.elements[i].selectedIndex = 0;
				}
			}
		}.bindTo(this.subcatUpdate.form));
	}

	/*Buttons fuer Weiterempfehlen im Firmeneintrag*/
	//facebook
	if(document.getElementById('facebookButtonLi')){
		document.getElementById('facebookButtonLi').innerHTML = 'Facebook: <iframe src="http://www.facebook.com/plugins/like.php?href='+document.location.href+'&amp;send=false&amp;layout=button_count&amp;width=290&amp;show_faces=false&amp;action=recommend&amp;colorscheme=light&amp;font=verdana&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:290px; height:21px;" allowTransparency="true"></iframe>';
	}

	//twitter
	if(document.getElementById('twitterButtonLi')){
		var twitterWidgets = document.createElement('script');
		twitterWidgets.type = 'text/javascript';
		twitterWidgets.async = true;
		twitterWidgets.src = 'http://platform.twitter.com/widgets.js';
		document.getElementsByTagName('head')[0].appendChild(twitterWidgets);
		document.getElementById('twitterButtonLi').innerHTML = 'Twitter: <a href="http://twitter.com/share" class="twitter-share-button" data-via="Gewerbeauskunft.com" data-count="none" data-lang="de">Twittern</a>';
	}

	//google plusone
	if(document.getElementById('plusone-div')){
		var g = document.createElement('script'),
			s = document.getElementsByTagName('script')[0];
		g.async = true;
		g.src = 'https://apis.google.com/js/plusone.js';
		g.innerHtml='{lang: \'de\', parsetags:\'explicit\'}';
		s.parentNode.insertBefore(g, s);

		myInterval = window.setInterval(function(){
			if(typeof gapi !='undefined'){
				window.clearInterval(myInterval);
				gapi.plusone.render('plusone-div',{"size": "medium", "count": "false"});
			}
		},100);
	}

	/* bookmarks im foot*/
	var locHrefUrlEnc = encodeURIComponent(document.location.href);
	var pageTitelUrlEnc = encodeURIComponent(document.title);
	var bkmLinks = {
		'0':'www.webnews.de/einstellen?url='+locHrefUrlEnc+'&amp;title='+pageTitelUrlEnc,
		'16':'www.oneview.de/quickadd/neu/addBookmark.jsf?URL='+locHrefUrlEnc+'&amp;title='+pageTitelUrlEnc,
		'32':'www.stumbleupon.com/submit?url='+locHrefUrlEnc+'&amp;title='+pageTitelUrlEnc,
		'48':'linkarena.com/bookmarks/addlink/?url='+locHrefUrlEnc+'&amp;title='+pageTitelUrlEnc+'&amp;desc=&amp;tags=',
		'64':'digg.com/submit?phase=2&amp;url='+locHrefUrlEnc+'&amp;bodytext=&amp;tags=&amp;title='+pageTitelUrlEnc,
		'80':'www.favit.de/submit.php?url='+locHrefUrlEnc,
		'96':'www.icio.de/add.php?url='+locHrefUrlEnc,
		'112':'www.mister-wong.de/index.php?action=addurl&amp;bm_url='+locHrefUrlEnc+'&amp;bm_notice=&amp;bm_description='+pageTitelUrlEnc+'&amp;bm_tags=',
		'128':'social-bookmarking.seekxl.de/?add_url='+locHrefUrlEnc+'&amp;title='+pageTitelUrlEnc,
		'144':'www.folkd.com/submit/[%locationHrefUrlEnc%]',
		'160':'www.linksilo.de/index.php?area=bookmarks&amp;func=bookmark_new&amp;addurl='+locHrefUrlEnc+'&amp;addtitle='+pageTitelUrlEnc,
		'176':'www.readster.de/submit/?url='+locHrefUrlEnc+'&amp;title='+pageTitelUrlEnc,
		'192':'yigg.de/neu?exturl='+locHrefUrlEnc,
		'208':'del.icio.us/post?v=2&amp;url='+locHrefUrlEnc+'&amp;notes=&amp;tags=&amp;title='+pageTitelUrlEnc,
		'224':'www.favoriten.de/url-hinzufuegen.html?bm_url='+locHrefUrlEnc+'&amp;bm_title='+pageTitelUrlEnc,
		'240':'reddit.com/submit?url='+locHrefUrlEnc+'&amp;title='+pageTitelUrlEnc
	};
	var bookmarks = document.getElementById("socialBookmarks");
	if(typeof bookmarks!='undefined' && bookmarks!=null) {
		for (var i in bkmLinks) {
			link = document.createElement('a');
			link.href='http://'+ bkmLinks[i];
			link.style.backgroundPosition = '-'+i+'px 0';
			link.className= 'bookmarkSprite';
			link.target='_blank';
			bookmarks.appendChild(link);
		}
	}
});

