
var url = new Object;
//url.baseUrl = 'http://localhost/johann/branchentool/index.php/';
url.baseUrl = 'http://1-position.de/geo_branchen/index.php/';
url.applicationUrl = null;

var branchen = null;

var maxSizeBranchen = [32, 32]; // Breite, Höhe
var maxSizeFirmen = [75, 75]; // Breite, Höhe

var areaCircleKm = 50; // Umkreissuche

/**
 *	Füllt ein Select-Feld mit Branchen-Optionen
 */
 var branchenSelectOptions = null;
(function($){

	$.fn.branchenSelect = function(opt) {
	
	    $.branchenSelect(this, opt);
	    
	    return this;
	}
	
	$.branchenSelect = function (target, opt) {
				
		opt = $.extend({
			_target: target,
			startValue: null,
			stadt: null
		}, opt);
		
		branchenSelectOptions = opt;
		
		$.ajax({
			type: 'GET',
			url: url.baseUrl+'b10l/Branche/export/',
			cache: false,
			dataType: 'json',
			success: function(data) {
				branchen = data;
				
				var options = '';
				for (var i=0; i<data.entries.length; i++) {
					options += '<option value="'+data.entries[i].id+'">'+data.entries[i].name+'</option>';
				}
				target.append(options);
				
				if (opt.startValue) {
					target.attr('value', opt.startValue);
				}
				
				url.applicationUrl = data.url;
			},
			error:function (xhr, ajaxOptions, thrownError){
				alert(thrownError);
	    }    
		});
		
		$(target).bind(
				'change', 
				function () {
					
					var id_branche = $(this).attr('value');

					expandGoogleMapWithFirma(gmap, id_branche, branchenSelectOptions.stadt);
				}
		);
		
		var code = '';
	}
	
})(jQuery);

var last_i = null;

/**
 *	Erweitert die GoogleMap um die Brancheneinträge aus der DB
 */
var address_info = [];
var global_markers = [];
var global_address = [];

var branchenIcons = [];
var branchenIconSizes = [];
var branchenNames = [];

var callUrl = null;
function expandGoogleMapWithFirma(map, id_branche, stadt) {

	callUrl = url.baseUrl+'b10l/Firma/export/?stadt='+stadt;
	if (id_branche) {
		callUrl += '&id_branche='+id_branche;
	}

	for (var i=0; i<global_markers.length; i++) {
		map.removeOverlay( global_markers[i] );
	}

	var geocoder = new GClientGeocoder();
	
	geocoder.getLatLng (
		stadt+', Deutschland',
		function(point) {

			$.ajax({
				type: 'GET',
				url: callUrl+'&breite='+point.lat()+'&laenge='+point.lng()+'&distance='+areaCircleKm,
				cache: false,
				dataType: 'json',
				success: function(data) {
		
					for(var i=0; i<branchen.entries.length; i++) {
						if (branchen.entries[i].flag != '') {
							branchenNames[branchen.entries[i].id] = branchen.entries[i].name;
							branchenIcons[branchen.entries[i].id] = branchen.entries[i].flag;
							if (branchen.entries[i].flagsize) {
								branchenIconSizes[branchen.entries[i].id] = branchen.entries[i].flagsize;
							}
						}
					}
					
					var geocoder = new GClientGeocoder();
					
					var address = null;
					var text = null;
					
					var thisIcon = null;
					var markers = [];
					var points = [];
					var coordKey = null;
					
					var options = '';
					for (var i=0; i<data.entries.length; i++) {
						
						if (branchenIcons[data.entries[i].id_branche]) {
							
							var size = [16, 16];
							if (branchenIconSizes[data.entries[i].id_branche]) {
								size = resizeImage(
									branchenIconSizes[data.entries[i].id_branche][0],
									branchenIconSizes[data.entries[i].id_branche][1],
									maxSizeBranchen[0],
									maxSizeBranchen[1]
								);
							}
		
							thisIcon = new GIcon();
							thisIcon.image = data.url+branchenIcons[data.entries[i].id_branche];
							thisIcon.shadow = '';
							thisIcon.iconSize = new GSize(size[0], size[1]);
							thisIcon.shadowSize = new GSize(0, 0);
							thisIcon.iconAnchor = new GPoint(6, 20);
							thisIcon.infoWindowAnchor = new GPoint(0, 0);
						}
						else {
							thisIcon = icon;
						}
						
						text = data.entries[i].name+'<br/>'+branchenNames[data.entries[i].id_branche];
						coordKey = '('+data.entries[i].breite+', '+data.entries[i].laenge+')';
		
						address_info[coordKey] = {
							infowindowtext: text,
							branche: branchenNames[data.entries[i].id_branche]
						}
						points[coordKey] = new GLatLng(data.entries[i].breite, data.entries[i].laenge);
					  markers[coordKey] = new GMarker(points[coordKey], thisIcon);
						global_markers[global_markers.length] = markers[coordKey];
						global_address[coordKey] = data.entries[i];
		
					  GEvent.addListener(markers[coordKey], 'click', function(coordKey) {
					  	
					  	var firma = global_address[coordKey];
					  	
					  	if (firma.icon) {
					  		
					  		size = resizeImage(
									firma.iconsize[0],
									firma.iconsize[1],
									maxSizeFirmen[0],
									maxSizeFirmen[1]
								);
					  		
					  		var icon = '';
					  		
								icon += '<div>';
								icon += '<img src="'+url.applicationUrl+firma.icon+'" width="'+size[0]+'" height="'+size[1]+'" />';
								icon += '</div>';
					  	}
					  	
					  	var html = '';
					  	
					  	html += '<div style="font-family: Tahoma; font-size: 12px; float:left;">';
					  	
					  	if (icon) {
					  		html += '<table><tr valign="top"><td>';
					  	}
							else {
								html += '<br/>';
							}
		
					  	html += '<b>'+firma.name+'</b><br/>';
					  	html += firma.strasse+'<br/>';
					  	html += firma.plz+', '+firma.stadt+'<br/>';
					  	
					  	if (firma.telefon != '') {
					  		html += 'Tel: '+firma.telefon+'<br/>';
					  	}
					  	html += '<br/>';
					  	html += address_info[coordKey].branche+'<br/>';
					  	
					  	if (icon) {
					  		html += '</td><td width="10" nowrap><div/></td><td>'+icon+'</td><td width="10" nowrap><div/></td></tr></table>';
					  	}
					  	
					  	html += '<br/>';
					  	html += 'Bewertungen: <span id="num_bewertung_general">'+firma.bewertung.num+'</span> (davon <span id="num_bewertung_positive">'+firma.bewertung.positiv+'</span> positiv)<br/>';
					  	html += '<br/>';
					  	
					  	html += '<form id="form_bewertung">';
					  	html += '<fieldset><legend>Ihre Bewertung</legend>';
					  	html += '<select name="bewertung" id="bew_bewertung"><option value="1">+</option><option value="0">-</option></select>';
					  	html += '<br/>';
					  	html += '<textarea name="kommentar" id="bew_kommentar"></textarea>';
					  	html += '<br/>';
					  	html += '<input type="button" value="Bewerten" onclick="sendRateRequest(\''+coordKey+'\');" />';
					  	html += '</fieldset>';
					  	html += '</form>';
					  	
					  	html += '<br/>';
					  	html += '<div id="showBewertung"><a href="#" onclick="showRates(\''+coordKey+'\')">Bewertungen anzeigen</a></div>';
					  	
					  	html += '</div>';
							
							markers[coordKey].openInfoWindowHtml(html);
						});
						GEvent.addListener(markers[coordKey], 'mouseover', function(coordKey) {
							
							var firma = global_address[coordKey];
							
							var html = '';
							
							html += '<div style="font-family: Tahoma; font-size: 12px;">';
					  	
					  	html += '<br/>';
					  	html += '<b>'+firma.name+'</b><br/>';
					  	html += firma.strasse+'<br/>';
					  	html += firma.plz+', '+firma.stadt+'<br/>';
					  	
					  	if (firma.telefon != '') {
					  		html += 'Tel: '+firma.telefon+'<br/>';
					  	}
					  	html += '<br/>';
					  	html += address_info[coordKey].branche+'<br/>';
							
							markers[coordKey].openInfoWindowHtml(html);
						});
						map.addOverlay(markers[coordKey]);
					}
				},
				error:function (xhr, ajaxOptions, thrownError){
					alert(thrownError);
		    }    
			});
	
		}
	);
}

function showRates(coordKey) {
		
	var firma = global_address[coordKey];
	
	var callUrl = url.baseUrl+"b10l/Bewertung/export/?data[id_firma]="+firma.id;

	$.ajax({
		type: 'GET',
		url: callUrl,
		cache: false,
		dataType: 'json',
		success: function(data) {
			
			var html = '';
			
			if (data.entries.length == 0) {
				
				html += 'Noch keine Bewertungen';
				
			} else {
				
				for (var i=0; i<data.entries.length; i++) {
					
					html += '<div style="float: left; font-weight: bold;">'+(data.entries[i].bew_bewertung ? '+' : '-')+'</div>';
					html += '<div style="float: left; padding-left: 10px;">'+(data.entries[i].bew_kommentar)+'</div>';
					html += '<br style="clear: both;" />';
					
					if (i == 6) break;
				}
			}
			
			$('#showBewertung').html(html);
			$('#form_bewertung').hide();
		}
	});
}

function sendRateRequest(coordKey) {
	
	var firma = global_address[coordKey];
	var bewertung = $("#bew_bewertung").attr("value");
	var kommentar = $("#bew_kommentar").attr("value");
	
	if (bewertung == '' || kommentar == '') {
		alert('Bitte geben Sie Ihre Bewertung und ein Kommentar ab');
	}
	else {
		
		var callUrl = url.baseUrl+"b10l/Bewertung/save/?data[id]="+firma.id+"&data[bewertung]="+bewertung+"&data[kommentar]="+kommentar;
		
		$.ajax({
			type: 'GET',
			url: callUrl,
			cache: false,
			dataType: 'json',
			success: function(data) {
				
				alert(data.message);
				
				if (data.status) {
					
					var val = $('#num_bewertung_general').html();
					val = parseInt(val);
					val++;
					$('#num_bewertung_general').html(val);
					
					var rate = $('#bew_bewertung').attr('value');
					rate = parseInt(rate);
					if (rate == 1) {
						var val = $('#num_bewertung_positive').html();	
						val = parseInt(val);
						val++;
						$('#num_bewertung_positive').html(val);
					}
				}
				
				$('#form_bewertung').hide();
			}
		});
	}
}

function resizeImage(width, height, maxWidth, maxHeight) {
	
	if (maxWidth && width > maxWidth) {

		var rel = (maxWidth / width);
		width = maxWidth;
		
		height = Math.round(height * rel);
	}
	if (maxHeight && height > maxHeight) {
		
		var rel = (maxHeight / height);
		height = maxHeight;
		
		width = Math.round(width * rel);
	}
	
	return [width, height];
}

var gmap = null;
function setMapCenter(map, thisStadt, zoom) {

	gmap = map;
	
	var geocoder = new GClientGeocoder();
	
	geocoder.getLatLng (
		thisStadt+', Deutschland',
		function(point) {
			
			gmap.setCenter(point, zoom);
		}
	);
}

/**
 *	Ermittelt die Breiten- und Längengrade zu einer Adresse und leitet diese an ein Script zum Speichern weiter
 *
 *	@param str stadt (Die Stadt, wofür die Firmen lokalisiert werden sollen)
 */
var firma;
var firma_counter = 0;
var stadt = null;
function initializeAddressConverting(thisStadt) {
	
	stadt = thisStadt;

	$.ajax({
		type: 'GET',
		url: url.baseUrl+'b10l/Firma/export/?mode=converting'+(thisStadt=='' ? '' : '&stadt='+thisStadt),
		cache: false,
		dataType: 'json',
		success: function(data) {

			var geocoder = new GClientGeocoder();
			
			var address = null;

			for (var i=0; i<data.entries.length; i++) {
				
				address = data.entries[i].strasse+', '+(data.entries[i].plz ? data.entries[i].plz : '')+', Deutschland';
				firma = data.entries[i];
	
				geocoder.getLatLng (
					address,
					function(point) {

						if ( ! point) {

							$.ajax({
								type: 'GET',
								url: url.baseUrl+'b10l/Firma/coord/?id='+firma.id+'&laenge=100&breite=100',
								cache: false,
								dataType: 'json',
								success: function(data) {
									
									$('#infoMessage').html('Firma-Counter: '+firma_counter+'<br/>id: '+firma.id+'<br/>name:'+firma.name+'<br/>Adresse nicht gefunden');
								}
							});

						}
						else {
	
							firma_counter++;
	
							if (firma.strasse) {
								
								$.ajax({
									type: 'GET',
									url: url.baseUrl+'b10l/Firma/coord/?id='+firma.id+'&laenge='+point.lng()+'&breite='+point.lat(),
									cache: false,
									dataType: 'json',
									success: function(data) {
										
										$('#infoMessage').html('Firma-Counter: '+firma_counter+'<br/>id: '+firma.id+'<br/>name:'+firma.name+'<br/>address: '+address+'<br/>url: '+url.baseUrl+'b10l/Firma/coord/?id='+firma.id+'&laenge='+point.lng()+'&breite='+point.lat()+'<br/>response: '+data.message);
									}
								});
							}
							else {

								$.ajax({
									type: 'GET',
									url: url.baseUrl+'b10l/Firma/coord/?id='+firma.id+'&laenge=100&breite=100',
									cache: false,
									dataType: 'json',
									success: function(data) {
										
										$('#infoMessage').html('Firma-Counter: '+firma_counter+'<br/>id: '+firma.id+'<br/>name:'+firma.name+'<br/>Adresse nicht gefunden');
									}
								});
							}
						}
						
						initializeAddressConverting(stadt);
					}
				);
				
				break;
			}
		}
	});
}
