var timer;

$(document).ready(function() {
	//$('#einrichtung-tabs').tabs();
//	$('.ui-tabs').tabs();

	/* Fancybox */
	$('a[rel=fb_einrichtung_bilder]').fancybox();
	$('a.fb').fancybox();
	$('a.fb-termin').fancybox({
		'width'				: 660,
		'height'			: 600,
        'autoScale'     	: false,
        'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe',
		'padding'			: 0
	});
   // $('#kalender-34').click();

	$('a.fb-news').fancybox({
		'width'				: 660,
		'height'			: 600,
        'autoScale'     	: false,
        'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe',
		'padding'			: 0
	});
	$("a.stellenangebote").fancybox({
		'width'				: 660,
		'height'			: 600,
        'autoScale'     	: false,
        'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe',
		'padding'			: 0
	});
	$("a.monster").fancybox({
		'width'				: 900,
		'height'			: 600,
        'autoScale'     	: false,
        'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe'
	});
	$("a.weiterempfehlen").fancybox({
		'width'				: 600,
		'height'			: 600,
        'autoScale'     	: false,
        'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe'
	});
	$("a.adresse_melden").fancybox({
		'width'				: 770,
		'height'			: 920,
        'autoScale'     	: false,
        'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe'
	});
	$("a.video").fancybox({ 
		'titleShow'			: false
	}); 

	// Netzwerk
	$('#einrichtung-auswahl').flexbox('ajax_selecteinrichtung.php',{
		width: 360,  
		showArrow: false,
//		autoCompleteFirstMatch: true ,

		 paging: {  
		     style: 'input',             // or 'links'  
		     cssClass: 'paging',         // prefix with containerClass (e.g. .ffb .paging)  
		     pageSize: 10,               // acts as a threshold.  if <= pageSize results, paging doesn't appear  
		     showSummary: true,          // whether to show 'displaying 1-10 of 200 results' text  
		     summaryClass: 'summary',    // class for 'displaying 1-10 of 200 results', prefix with containerClass  
		     summaryTemplate: 'Zeige {start}-{end} von {total} Ergebnissen' // can use {page} and {pages} as well  
		 },
		watermark: 'Einrichtung suchen',  
		onSelect: function() {  
//			$('#einrichtung').val(  );

			$('#auswahl-result').load('index.php?s=ajax_dataadd&id='+ this.getAttribute('hiddenValue'));
			
		}
	
	});	
	$('#einrichtung-auswahl-admin').flexbox('ajax_selecteinrichtung.php',{
		width: 360,  
		showArrow: false,
//		autoCompleteFirstMatch: true ,

		 paging: {  
		     style: 'input',             // or 'links'  
		     cssClass: 'paging',         // prefix with containerClass (e.g. .ffb .paging)  
		     pageSize: 10,               // acts as a threshold.  if <= pageSize results, paging doesn't appear  
		     showSummary: true,          // whether to show 'displaying 1-10 of 200 results' text  
		     summaryClass: 'summary',    // class for 'displaying 1-10 of 200 results', prefix with containerClass  
		     summaryTemplate: 'Zeige {start}-{end} von {total} Ergebnissen' // can use {page} and {pages} as well  
		 },
		watermark: 'Einrichtung suchen',  
		onSelect: function() {  
//			alert('Einrichtung:'+this.getAttribute('hiddenValue'));
//			$('#auswahl-result').load('index.php?s=ajax_dataadd&id='+ this.getAttribute('hiddenValue'));
			$('#netzwerk').val( this.getAttribute('hiddenValue') );
			$('#netzwerk-anlegen').show();
		}
	
	});	
	//$('#einrichtung-auswahl').flexbox('index.php?s=ajax_selecteinrichtung');	
	
	// Ajax-Filter
	$('.ajax-filter .filter-select').change(function(){		
		$('#pg').val( 1 );
		einrichtungen_filter();		
	});

	
	$('.ajax-filter .filter-text').keyup(function(){		
		$('#pg').val( 1 );
		clearTimeout( timer );
		timer=setTimeout(function validate(){
			einrichtungen_filter();
		},1000);
				
	});

	$('#einrichtung-numberOf').change( function() {
		$('#pg').val( 1 );
		einrichtungen_filter();
	});	
	
	// Tabs
	//$('#einrichtung-tabs').tabs();
	$('.ui-tabs').tabs();
	$('#be-einrichtung-tabs').tabs({
	    select: function(event, ui) {
			//var $tabs = $('#example').tabs();
			//var selected = $(this).tabs('option', 'selected'); // => 0
	        $('#tab').val( ui.index );
			return true;
	    }
	
	});
	$('#aktuelles-tabs').tabs();

	// Stylish-Select
	$('.form-layer select').sSelect();
	$('#filter select').sSelect();
	$('select.gn-select').sSelect();
	$('select.lexikon-select').sSelect();
	
	
	$('#lexikon-select select').change( function(){
		var link = $( this ).attr( 'link' )+$( this ).val();
		window.location.href = link; 
	});

	// Datepicker 
	$(".datepicker").datepicker({ 
	    showOn: "button", 
	    buttonImage: "components/datepicker/datepicker.png", 
	    buttonImageOnly: true
	}).addClass("embed");
	
	// Multiselect 
	$('.branche_be #branche').multiSelect(   
	{   
		select_all_min: 3,   
		no_selection: "Bitte Branchen auswählen",   
		selected_text: " Branche(n) ausgewählt"
	}); 	
	
	if( get_get_param( 's' ) == 'einrichtung' && get_get_param( 'id' ) == false && get_get_param( 'urlname' ) == false )
	{
		einrichtungen_filter();
	}
	
	// Bei Registrierung Voreinstellung der Branchen
	if( get_get_param( 's' ) == 'registrierung' )
	{
		
		if( $('#bereich').val() != 0 && $('#bereich').val() != "" )
		{
			if( $('#einrichtung-branche-id').val() != '' )
				var strValue = '&v='+parseInt( $('#einrichtung-branche-id').val() );
			else
				var strValue = '';
			
			$('#branche').load( 'index.php?s=ajax_branchen&e=0&bereich='+parseInt( $('#bereich').val() )+strValue, function() {
				$('#branche').resetSS();
			});
		}	
	}
	
	// Branchen nachladen ( Erweiterte Suche )
	$('#filter_bereich').change( function() {
		$('#filter_branche').load( 'index.php?s=ajax_branchen&e=1&bereich='+$(this).val(), function() {
			$('#filter_branche').resetSS();
			$('#filter_branche').bind('change', function() {
				$('#pg').val( 1 );
				einrichtungen_filter();		
			});
			einrichtungen_filter();	
		});
	});
	
	// Branchen nachladen
	$('#bereich').change( function() {
		$('#branche').load( 'index.php?s=ajax_branchen&e=0&bereich='+parseInt( $(this).val() ), function() {
			$('#branche').resetSS();
		});
	});
	
	// Status ändern
	$('.change-status').click( function() {
		
		
		$.ajax({
			url: ('index.php?s=ajax_status&etype='+$(this).attr('etype')+'&eid='+$(this).attr('eid') ),
			data: getFilterParamsStr(),
			type: 'GET',
			cache: false,
			timeout: 100000
		});
		if( $(this).attr('status') == 1 )
			$(this).attr('src','img/status_0.png');
		else	
			$(this).attr('src','img/status_1.png');
		
	});
	
	$('.statistik').click( function() {
		$.ajax({
			url: ('index.php?s=ajax_statistik'),
			data: 'type=' + $(this).attr('t') +'&id='+ $(this).attr('cid'),
			type: 'GET',
			cache: false,
			timeout: 100000,
			dataType: 'json',
			error: function(xhr, status, errorThrown) {
			alert('Error loading json data (1)!'+xhr+status+errorThrown);
			},
			success: function(json) {}
		});		
	});
	
	// Galerien ein- und ausblenden
	$('.showhide-galerie').click( function(){
		$('#galerie-' + $(this).attr('gid') ).toggle();
		if( $('#galerie-' + $(this).attr('gid') ).css('display') == 'block' )
			$('img#showhide-galerie-' + $(this).attr('gid') ).attr( 'src', 'img/galerie-hide.gif' );
		else	
			$('img#showhide-galerie-' + $(this).attr('gid') ).attr( 'src', 'img/galerie-show.gif' );
	});
	
	// Termine, Bews und Jobs ein- und ausblenden
	$('.showhide-tnj').click( function(){
		$('#tnj-' + $(this).attr('gid') ).toggle();
		if( $('#tnj-' + $(this).attr('gid') ).css('display') == 'block' )
			$('img#showhide-tnj-' + $(this).attr('gid') ).attr( 'src', 'img/galerie-hide.gif' );
		else	
			$('img#showhide-tnj-' + $(this).attr('gid') ).attr( 'src', 'img/galerie-show.gif' );
	});
	
	// Tooltipp
	$('.info').tooltip({ 
		showURL: false 
	});
	
	// Öffnungszeiten
	var oeffnungszeiten_add_cnt = 100;
	$('#oeffnungszeiten-add').click( function() {
		var strTr = '<tr><td class="tag"><input type="texte" name="oeffnungszeiten2[n'+oeffnungszeiten_add_cnt+'][0]" value=""/></td><td class="zeit"><input type="texte" name="oeffnungszeiten2[n'+oeffnungszeiten_add_cnt+'][1]" value=""/></td><td class="zeit"><input type="texte" name="oeffnungszeiten2[n'+oeffnungszeiten_add_cnt+'][2]" value=""/></td></tr>';
		oeffnungszeiten_add_cnt++;
		$('#oeffnungszeiten-tr-add').before( strTr );
	});
	
	// Netzwerk 
	$('#netzwerk-slider').vScroll({ 
		speed: 500, 
		upID: "#prevButton", 
		downID: "#nextButton" 
	});

	$('#checkbox-all').click(function(){
		if( $(this).attr("checked") )
			$('.checkbox-list').attr('checked','checked');

		else
			$('.checkbox-list').removeAttr('checked');
	});
});

function loadStatistik( id )
{
	location.href = 'index.php?s=admin_einrichtungen&t=edit&id='+id+'&dv='+$('#datumvon').val()+'&db='+$('#datumbis').val()+'#tab5';
}	

function get_get_params () {
   var GET = new Array();
   if(location.search.length > 0) 
   {
      var get_param_str = location.search.substring(1, location.search.length);
      var get_params = get_param_str.split("&");
      for(i = 0; i < get_params.length; i++) 
	  {
         var key_value = get_params[i].split("=");
         if(key_value.length == 2) 
		 {
            var key = key_value[0];
            var value = key_value[1];
            GET[key] = value;
         }
      }
   }
   return(GET);
}

function get_get_param(key) 
{
   var get_params = get_get_params();
   if(get_params[key])
      return(get_params[key]);
   else
      return false;
}

function sucheNext( )
{
	$('#pg').val( parseInt( $('#pg').val() ) + 1 );
	einrichtungen_filter();
}
function suchePrev( )
{
	$('#pg').val( parseInt( $('#pg').val() ) - 1 );
	einrichtungen_filter();
}

function einrichtungen_filter()
{
	var pg = parseInt( $('#pg').val() );
	var num = parseInt( $('#einrichtung-numberOf').val() );
	$('.suchergebnisse').hide();
	$('img.loading').show();


	if( pg == 1 )
		$('#suche-prev').hide();
	else	
		$('#suche-prev').show();
	
	//alert('index.php?s=ajax_einrichtungen_filter&num='+num+'&pg='+pg+'-'+getFilterParamsStr());
	$.ajax({
		url: ('index.php?s=ajax_einrichtungen_filter&num='+num+'&pg='+pg),
		data: getFilterParamsStr(),
		type: 'GET',
		cache: false,
		timeout: 100000,
		dataType: 'json',
		error: function(xhr, status, errorThrown) {
			alert('Error loading json data (2)!'+xhr+status+errorThrown);
			//alert('Timeout: Bitte versuchen Sie es noch einmal');
		},
		success: function(json)
		{
			var output = '';
			var anzahl = 0;
			var i = 0;
			for (p in json) 
			{
				// Liste
				if( json[p].preview != '' && ( json[p].paket == 1 || json[p].paket == 2 ) )
				{
					if( parseInt( json[p].previewwidth ) > 90 )
						var bildwidth = ' width="90" ';
					else
						var bildwidth = '';
					var bild = '<a href="'+json[p].link+'" title=""><img src="'+json[p].preview+'" alt="'+json[p].firma+'" title="'+json[p].firma+'" '+bildwidth+'></a>';
				}
				else
					var bild = '&nbsp;';
				if( json[p].website != '' && ( json[p].paket == 1 || json[p].paket == 2 ) )
					var strWebsite = '<a href="'+json[p].website+'" title="Zur Website der Einrichtung" target="_blank"><img src="img/icon-website.png" alt="Website"/></a>';
				else
					var strWebsite = '';
				if( json[p].lat != '' && json[p].lon != '' )
					var strKarte = '<a href="'+json[p].link+'#tab3" title="Einrichtung auf Karte anzeigen"><img src="img/icon-karte.png" alt="Karte"/></a>';
				else
					var strKarte = '';
				if( json[p].anznews == 0 )
					var strNews = '';
				else
					var strNews = '<a href="'+json[p].link+'" title="Aktuelles vorhanden"><img src="img/tnj-news.png" alt="Aktuelles"/></a>';
				if( json[p].anztermine == 0 )
					var strTermine = '';
				else
					var strTermine = '<a href="'+json[p].link+'" title="Termine vorhanden"><img src="img/tnj-termine.png" alt="Termine"/></a>';
				if( json[p].anzjobs == 0 )
					var strJobs = '';
				else
					var strJobs = '<a href="'+json[p].link+'" title="Stellenangebote vorhanden"><img src="img/tnj-jobs.png" alt="Stellenangebote"/></a>';
				if( json[p].video == 0 )
					var strVideo = '';
				else
					var strVideo = '<a href="'+json[p].link+'" title="Video vorhanden"><img src="img/icon-video.png" alt="Video vorhanden"/></a>';
				
				if( i%2 == 0 )
					var divclass = 'div-even';
				else
					var divclass = 'div-odd';
			
				output += 	'<div class="einrichtung '+ divclass +'">'+
								'<div class="einrichtung-bild">'+bild+'</div>'+
								'<div class="einrichtung-daten"><a href="'+json[p].link+'" title="">'+json[p].firma+'</a><br/>'+json[p].strasse+'<br/>'+json[p].plz+' '+json[p].ort+'</div>'+
								'<div class="einrichtung-bereich">'+json[p].bereichbranche+'</div>'+
								'<div class="einrichtung-info"><a href="'+json[p].link+'" title="">&raquo; Mehr Informationen</a><br/>'+strKarte+strWebsite+strNews+strTermine+strJobs+strVideo+'</div>'+
								'<div class="clr"></div>'+
							'</div>';
				
				// Werbung
				i++;
				anzahl = json[p].anzahl;
				if( ( i == 4 && json[p].werbung_id != '' ) || ( json[p].werbung_id != '' && i < 4 && i == anzahl  ) )
				{
					if( json[p].werbung_code == '' )
						var strCode = '<a href="index.php?s=s_banner&id='+json[p].werbung_id+'" target="_blank"><img src="'+json[p].werbung_img+'" alt="" title=""/></a>';
					else
						var strCode = json[p].werbung_code;
					output += 	'<div class="content-ad">'+strCode+'</div>';
				}
			}

			var pg = parseInt( $('#pg').val() );
			var num = parseInt( $('#einrichtung-numberOf').val() );

			$('#suchergebnisse').html(output);
			$('.suchergebnisse-anzahl').text( anzahl );
			$('img.loading').hide();
			$('.suchergebnisse').show();
			if( anzahl == 0 )
				$('.stellenangebote-navigation').hide();
			else
				$('.stellenangebote-navigation').show();
			var intMaxpages = parseInt( Math.ceil ( anzahl / num ) );		

			if( pg < intMaxpages )
				$('#suche-next').show();
			else	
				$('#suche-next').hide();

			$('.suchergebnisse-von').text( parseInt( ( ( pg - 1 ) * num ) + 1 ) );
			var bis = parseInt( pg * num );
			if( bis > anzahl)
				bis = anzahl;
			$('.suchergebnisse-bis').text( bis );

				
		}
	});
	
		
	

}
function einrichtungen_filter_map()
{
	$('#karte').hide();
	$('#loading').show();
	$.ajax({
		url: ('index.php?s=ajax_einrichtungen_filter'),
		//data: 'stichwort=' + $("#filter_stichwort").val() +'&plzort='+ $("#filter_plzort").val() +'&branche='+ $("#filter_branche").val() +'&bereich='+ $("#filter_bereich").val() +'&umkreis='+ $("#filter_umkreis").val(),
		data: getFilterParamsStr()+'&num='+$('#filter_num').val()+'&pg='+$('#filter_pg').val(),
		type: 'GET',
		cache: false,
		timeout: 100000,
		dataType: 'json',
		error: function(xhr, status, errorThrown) {
			alert('Error loading json data (3)!'+xhr+status+errorThrown);
			//alert('Timeout: Bitte versuchen Sie es noch einmal');
		},
		success: function(json)
		{
			map.clearOverlays();  // alle Marker entfernen

			$('.loading').hide();
			$('#karte').show();
			
			//var output = 'Hier die Suchergebnisse<br/><br/>';
			for (p in json) 
			{
				// Karte
				var point = new GLatLng(json[p].lat, json[p].lon);
				var icon = new GIcon(G_DEFAULT_ICON);
				//icon.image = "http://www.europlan-online.de/img/default_icon.png";					
				//icon.shadow = '';
				//icon.iconSize = new GSize( 30, 30 );
				//icon.iconAnchor = new GPoint( 15, 15 );
				var marker = createMarker(point,'<div class="marker"><strong>'+json[p].firma+'</strong><br\/>'+json[p].strasse+'<br\/>'+json[p].plz+' '+json[p].ort+'<\/div>',icon);
				map.addOverlay(marker);
			}			
		}
	});
}
function getFilterParamsStr()
{
	return 'stichwort=' + $("#filter_stichwort").val() +'&plzort='+ $("#filter_plzort").val() +'&branche='+ $("#filter_branche").val() +'&bereich='+ $("#filter_bereich").val() +'&umkreis='+ $("#filter_umkreis").val();
}
function showMap()
{
	map = window.open('index.php?s=einrichtung-karte&fbShow=1&'+getFilterParamsStr()+'&num='+parseInt( $('#einrichtung-numberOf').val() )+'&pg='+parseInt( $('#pg').val() ),'Suchergebnisse','width=900,height=650,scrollbars=yes,toolbar=no,status=no,locationbar=no,menubar=no,resizable=yes,screenX=0,screenY=0,dependent=no');
    map.focus();
}	

// Google -Map Funktionen
function createMarker(point,html,icon) 
{
	var marker = new GMarker(point,icon);
    if( html != '' )
	{
		GEvent.addListener(marker, "click", function(){ 
			marker.openInfoWindowHtml(html);
	    });
	}
    return marker;
}

function getmapdata(map)
{
	$("#center").val( map.getCenter() );
	$("#zoom").val( map.getZoom() );
}

// Setzt den Marker auf die Karte
function stadienSetJS( map, center )
{
	marker = new GMarker(center, {draggable: true});
	
	GEvent.addListener(marker, "dragend", function() {
		$('#geodaten').val( marker.getLatLng() );
	});

	map.addOverlay(marker);

}

// Ermittellt die Koordinaten anhand der eingegebenen Adresse
function getAdressData()
{
	var address = $('#strasse').val()+','+$('#plz').val()+' '+$('#ort').val();
	
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(
	    address,
	    function(point) 
		{
			if (!point) 
			{
				alert("Adresse konnte nicht gefunden werden");
			} 
			else 
			{
				map.setCenter(point, 13);
				marker.setPoint(point);
				$('#geodaten').val( marker.getLatLng() );
				//var marker = new GMarker(point);
				//map.addOverlay(marker);
				//marker.openInfoWindowHtml(address);
			}
	    }
	);

}

			

function connect( user )
{
	if( confirm( $('#firma').val() + ' wirklich zum Netzwerk hinzufügen?' ) )
	{
		$.ajax({
			url: ('index.php?s=ajax_connect'),
			data: 'cid=' + $("#id").val(),
			type: 'GET',
			cache: false,
			timeout: 100000,
			dataType: 'json',
			error: function(xhr, status, errorThrown) {
				alert('Error loading json data (4)!'+xhr+status+errorThrown);
				//alert('Timeout: Bitte versuchen Sie es noch einmal');
			},
			success: function(json)
			{
				$('.connect-sh').hide();
				alert( $('#firma').val() + ' erhält eine Benachrichtigung zur Bestätigung' );
			}
		});
	}
}


// Setzt den Marker auf die Karte
function setMarker( map, center )
{
	marker = new GMarker(center, {draggable: true});
	
	GEvent.addListener(marker, "dragend", function() {
		var p = marker.getLatLng();
		$('#lat').val( p.lat() );
		$('#lon').val( p.lng() );
	});

	map.addOverlay(marker);

}

 /* 
  function initialize() 
  {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var chicago = new google.maps.LatLng(41.850033, -87.6500523);
    var myOptions = 
	{
      zoom:7,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: chicago
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
}
*/
function kundenlogin(u,p)
{
	document.getElementById('username').value = u;
	document.getElementById('password').value = p;
	document.getElementById('kundenlogin').submit();
}

function sendTestNewsletter(id)
{
	location.href="index.php?s=admin_newsletter&t=sendtest&id="+id+"&email="+document.getElementById('testempfaenger').value;
}

// Ermittellt die Koordinaten anhand der eingegebenen Adresse
function getAdressData()
{
	var address = $('#strasse').val()+','+$('#plz').val()+' '+$('#ort').val();
	
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(
	    address,
	    function(point) 
		{
			if (!point) 
			{
				alert("Adresse konnte nicht gefunden werden");
			} 
			else 
			{
				map.setCenter(point, 13);
				marker.setPoint(point);
				//$('#geodaten').val( marker.getLatLng() );
				var LatLng = new GLatLng( point.y,point.x);
				$('#lat').val( LatLng.lat() );
				$('#lon').val( LatLng.lng() );
			}
	    }
	);

}

