// JavaScript Document
var HTTP_SERVER = "http://www.deine-berge.de/";
var dbclick_color = "#CECFD1";

function ask(asktext){
    return confirm(asktext);
}

function rand(lo, hi) {
  return Math.floor(lo + Math.random() * (hi - lo));
}

Dec_Grad = function(dec,grad,Min,sek,richtung){
	var Dec = 0; var Grad = []; var temp = [];
	if(richtung == "Dec"){
		if(sek=="") sek = 0;
		if(grad<0) Dec = parseInt(grad) - (parseFloat(Min)/60) - (parseFloat(sek)/3600);
		else Dec = (parseFloat(sek)/3600) + (parseFloat(Min)/60) + parseInt(grad);
		return Dec.toFixed(6);
	}
	if(richtung == "Grad"){
		var temp_dec = String(dec).replace(/\,/,".");
		dec = temp_dec.split(".");
		Grad["grad"] = dec[0]; 
		var temp_min = String((temp_dec-dec[0])*60); 
		temp = temp_min.split(".");
		Grad["min"] = Math.abs(temp[0]);
		Grad["sek"] = Math.abs(((((temp_dec-dec[0])*60)-temp[0])*60).toFixed(6));
		return Grad;
	}
}

getMicrosoftGetTileUrl = function(coord,zoom,mapType,imgType,ka){ 
	for(var k=coord.x%(1<<zoom),l=coord.y,f="",d=zoom;d>0;d--){var g=1<<d-1,e=0;(k&g)!=0&&e++;if((l&g)!=0)e+=2;f+=e;} 
	return ["http://ecn.t",Math.floor(Math.random()*4),".tiles.virtualearth.net/tiles/h",f,"?g=737&n=z"].join("");	
}

function isInt(n) {
   return typeof n == 'number' && n % 1 == 0;
}

function in_array(item,arr) {
	for(p=0;p<arr.length;p++) if (item == arr[p]) return true; 
	return false;
}

function parseXml(str) {
	if (window.ActiveXObject) {
		var doc = new ActiveXObject('Microsoft.XMLDOM');
		doc.loadXML(str);
		return doc;
	} else if (window.DOMParser) {
		return (new DOMParser).parseFromString(str, 'text/xml');
	} else
		return "";
} 

debug = function(msg) {
	if (window.console && window.console.log)
		window.console.log(msg);
}

var getAdminUrl = HTTP_SERVER + "ajax/checkAdmin.php"; 

$(document).ready(
        function () {
			
		//$("button, input:submit, input:button").button();
			
		j = new Date();
		Jahr = j.getYear();
		if ((Jahr > 99) && (Jahr < 1900)) Jahr += 1900;
		$.datepicker.regional['de'] = {
			closeText: 'schlie&szlig;en',
			prevText: '&lt; zur&uuml;ck',
			nextText: 'Vor &gt;',
			currentText: 'heute',
			monthNames: ['Januar','Februar','M&auml;rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
			monthNamesShort: ['Jan','Feb','M&auml;r','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
			dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
			dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
			dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
			weekHeader: 'KW',
			dateFormat: 'dd.mm.yy',
			firstDay: 1,
			isRTL: false,
			showMonthAfterYear: false,
			yearSuffix: '',
			showOn:'focus',
			showStatus: true, 
			showWeek: true, 
			highlightWeek: true,  
			numberOfMonths: 1, 		
			changeYear: true,
			changeMonth: true,
			showOtherMonths: true,
			yearRange: '1900:'+(Jahr+1),
			//showAnim: "scale"
			};
		$.datepicker.setDefaults($.datepicker.regional['de']);
		
		$.timepicker.regional['de'] = {
			timeFormat: 'hh:mm:ss',
			timeOnlyTitle: 'Uhrzeit w&auml;hlen',
			timeText: 'Zeit',
			hourText: 'Stunde',
			minuteText: 'Minute',
			secondText: 'Sekunde',
			currentText: 'jetzt',
			closeText: 'fertig',
			showTime: false,
			ampm: false
		};
		$.timepicker.setDefaults($.timepicker.regional['de']);
		
		$('.datepicker').live('click', function() {
			var data = $(this).metadata();
			var datepickerOptions = new Object();
			if(data.startYear && data.startYear > 0) datepickerOptions['yearRange'] = ''+data.startYear+':'+(Jahr+1);
			$(this).datepicker(datepickerOptions).focus();
		});
		
		$('.timepicker').live('click', function() {
			var data = $(this).metadata();
			var TimepickerOptions = new Object();
			if(data.stepMinute && data.stepMinute > 0) TimepickerOptions['stepMinute'] = parseInt(data.stepMinute);
			if(data.stepHour && data.stepHour > 0) TimepickerOptions['stepHour'] = parseInt(data.stepHour);
			if(data.showSecond && data.showSecond > 0) TimepickerOptions['showSecond'] = data.showSecond;
			$(this).timepicker(TimepickerOptions).focus();
		});
			
			$("tr")
			.dblclick(function() { $(this).css("background-color",dbclick_color); })
			.click(function() { $(this).css("background-color",""); });
			
			$("img").error(function(){  $(this).hide(); });
			
			$(".fehler, .richtig").click(function() { $(this).fadeOut(); });
            
			var tooltip_title = null;
            $(".tooltip")
			.dblclick($.tooltip.block)
			.tooltip({ 
				bodyHandler: function() {  
					return $(this).next().html();
				},
				track: true,  
				delay: 0, 
				showURL: false, 
				titleHandler: function() {  
					return $(this).next().attr("title");
				}    
			})
			.hover(
			  function () {
				tooltip_title = $(this).attr("title");
				if(!$(this).hasClass("nyroModal")) $(this).attr("title","");
			  },
			  function () {
				$(this).attr("title",tooltip_title);
			  }
			);
			
            $(".tt_header").click(function(){$.tooltip.blocked=false;$('#tooltip').fadeOut(100);$.tooltip.handle;});
            
            $.tablesorter.addParser({
                id: 'datum',
                is: function(s) { return false; },   // return false so this parser is not auto detected
                format: function(s) { return s.replace(new RegExp(/(\d{1,2})[\.](\d{1,2})[\.](\d{4})/), "$3$2$1"); },
                type: 'numeric' // set type, either numeric or text
            });
            $.tablesorter.addParser({         
                id: 'title_text',
                is: function(s) {   return false; },
                format: function(value, table, cell) {  return $(cell).attr('title');   },
                type: 'text' 
            });
            $.tablesorter.addParser({
                id: 'title_num',
                is: function(s) {   return false; },
                format: function(value, table, cell) {  return $(cell).attr('title');   },
                type: 'numeric' 
            });
            $.tablesorter.addParser({
                id: 'id_num',
                is: function(s) { return false; },
                format: function(value, table, cell) { var id = $(cell).attr('id').split("_");  return id[1]; },
                type: 'numeric' 
            });
            $.tablesorter.addParser({
                id: 'id_text',
                is: function(s) { return false; },
                format: function(value, table, cell) { var id = $(cell).attr('id').split("_");  return id[1]; },
                type: 'text' 
            });
            $(".sortable").tablesorter({		widgets: [ 'stickyHeaders' ]	});
            
			$('.nyroModal').nyroModal({
				galleryLoop: true,

				/*// 1.6.2
				endFillContent: function(){
					$.tooltip.blocked=false;$('#tooltip').fadeOut(100);$.tooltip.handle;
				},
				endShowContent: function(elts) {
				  $('input:text:first', elts.content).focus();
				},
				endRemove: function(elts, settings) {
                    if ($(settings.from).attr('rev')){
						if ($(settings.from).attr('rev').match(/reload/)){
							var tempUrl = $(settings.from).attr('rev').split(':');
							if(tempUrl.length>1){
								top.window.location.href = "http://" + top.window.location.hostname + "/" + tempUrl[1];
							}else{
								top.window.location.href = top.window.location;
							}
						}
                    }   
                }*/
				
				// 2.0
				//debug: true, 
				//header: '<div class="nyroModalHeader"></div>',
				callbacks: {
					beforeShowCont: function(nm) {
						if(nm.store.title){
							if(nm.loadFilter == "image"){ 
								//nm.elts.cont.after('<div class="nyroModalHeader"></div>');
								//debug(nm.store.title.html());
								//var nyroTitle = nm.store.title.html();
								//$(".nyroModalHeader").html(nyroTitle).addClass("hiker");
							}else{
								nm.store.title.remove();
							}
						}
					},
					afterShowCont: function(nm) {
						$('input:text:first', nm.elts.cont).focus();
						//console.log(nm.opener.attr('rev'));
						/*$('.resizeLink', nm.elts.cont).click(function(e) {
							e.preventDefault();
							nm.sizes.initW = Math.random()*1000+200;
							nm.sizes.initH = Math.random()*1000+200;
							nm.resize();
						});*/
					},
					beforeShowBg: function(nm){ 
						//$('#nyroModalWrapper').draggable({ handle: '.h2_weiss, .handle, .drag' });
						$.tooltip.blocked=false; $('#tooltip').fadeOut(100); $.tooltip.handle;
						if(nm.opener.hasClass("fileUpload")) $(".nyroModalLoad").addClass("fileUpload"); else  $(".nyroModalLoad").removeClass("fileUpload");
					},
					afterClose: function(nm) {
						if(nm.opener.attr('rev')){
							if(nm.opener.attr('rev').match(/reload/)){
								var tempUrl = nm.opener.attr('rev').split(':');
								if(tempUrl.length>1){
									top.window.location.href = "http://" + top.window.location.hostname + "/" + tempUrl[1];
								}else{
									top.window.location.href = top.window.location;
								}
							}
						}   
					}
				}
				
			});
			
			
			//$.nmInternal({debug: true});
            
            $("#clear_suche").click(function () {
                $('#suchergebnis').fadeOut();
                $('.suchtext').attr("value","");
                return false;
            });
            
        function LiveSuche(e) {
			var inputString = $(".suchtext").attr("value");
			if(inputString.length == 0){ 
				$('#suchergebnis').fadeOut();
			}else{
				$('#suchergebnis').fadeIn(); // Show the result box
				if (inputString.length == 1){ 
					$('#suchergebnis').html('Live-Suche startet ab dem 2. Buchstaben ... <img src="'+HTTP_SERVER +'images/loading.gif" />');
				}
				if(inputString.length > 1) {
					$("#suchbegriff").attr("value",inputString);
					var suchkat = $("#suchkat").attr("value");
					$.get(HTTP_SERVER + "includes/suche.php", {suchkat: ""+suchkat+"",suche: ""+inputString+""}, function(data) { // Do an AJAX call
						$('#suchergebnis').html(data); // Fill the result box
					});
				}
			}
        }
        
		var isOpen = false;
		var isOpenSelect = false;
		var isOpenFreunde = false; 
		var isOpenNotes = false; 
		
		$("#open_freunde").click(function (e) {
			if(isOpen){ 
				isOpen.hide();
				isOpenNotes = false;
			}
			if(isOpenFreunde){  // Nachrichten Fenster ist eingeblendet
				isOpenFreunde = false;
				isOpen = false;
				$("#mini_freunde").hide();
				$(this).removeClass("fix_link_aktiv");
			}else{ // Nachrichten Fenster ist ausgeblendet (Standard)
				isOpenFreunde = true;
				isOpen = $("#mini_freunde");	
				$(".fix_link").removeClass("fix_link_aktiv"); 
				$(this).addClass("fix_link_aktiv");
				$("#mini_freunde").show();
				$.get(HTTP_SERVER + "ajax/mini_freunde.php", function(data){
					$("#mini_freunde").html(data);
				});
			}
			e.stopPropagation(); 
		});
		
		$("#open_notes").click(function (e) {
			if(isOpen){ 
				isOpen.hide();
				isOpenFreunde = false;
			}
			if(isOpenNotes){  // Nachrichten Fenster ist eingeblendet
				isOpenNotes = false;
				isOpen = false;
				$("#mini_notes").hide();
				$(this).removeClass("fix_link_aktiv");
			}else{ // Nachrichten Fenster ist ausgeblendet (Standard)
				isOpenNotes = true;
				isOpen = $("#mini_notes");	
				$(".fix_link").removeClass("fix_link_aktiv"); 
				$(this).addClass("fix_link_aktiv");
				$("#mini_notes").show();
				$.get(HTTP_SERVER + "ajax/mini_notes.php", function(data){
					$("#mini_notes").html(data);
				});
			}
			e.stopPropagation(); 
		});   
        
		$(".select_alternate_24").click(function (e) {
            $(".alter_content").hide();
			$(".select_alternate_24").removeClass("select_alternate_24_active");
			$(this).next().show();
			$(this).addClass("select_alternate_24_active");
			isOpenSelect = true;
			e.stopPropagation();
        });
		
		$(document.body).click(function(){     
			if(isOpenSelect){ 
				$(".alter_content").hide();
				$(".select_alternate_24").removeClass("select_alternate_24_active");
				isOpenSelect = false;
			}
			if(isOpen){ 
				isOpen.hide();
				$(".fix_link").removeClass("fix_link_aktiv"); 
				isOpenFreunde = false;
				isOpenNotes = false; 
			}
		});
        
        $("#suchkatid_content>li").click(function () {
            $('#suchkatid_content').hide();
            $('#select_suchkatid').attr("value",$(this).attr("title"));
            var id = $(this).attr('id').split("_");
            $('#suchkat').attr("value",id[1]);
            $("#suchkatid_content>li").removeClass("selected");
            $(this).addClass("selected");
            LiveSuche();
        });
    	
	 var timer = null;
	  function StartSuche(){
		if(timer)clearTimeout(timer);
		timer = setTimeout(LiveSuche, 150);
	  }
		
      $(".suchtext")
	  .keyup(function(){
	  	StartSuche();
	  })
	  .keydown(function(e){
			if (e.keyCode == 13) {
				$("#searchForm").submit();
				return false;
			}
	  });
		
		$(".add2fav").click( function(){
			var c = $(this).children();
			var t = $(this);
			t.html('<img src="'+HTTP_SERVER +'images/loading.gif" />');
			var id = c.attr("id").split("_");
			$.get(HTTP_SERVER + "includes/fav.php", {typ: ""+id[3]+"", typ_id: ""+id[1]+"", action: ""+id[2]+""}, function(data) {
                t.html(data); 
           });	
		});
		
		$(".add2gew").click( function(){
			var c = $(this).children();
			var t = $(this);
			t.html('<img src="'+HTTP_SERVER +'images/loading.gif" />');
			var id = c.attr("id").split("_");
			$.get(HTTP_SERVER + "includes/gewesen.php", {typ: ""+id[3]+"", typ_id: ""+id[1]+"", action: ""+id[2]+""}, function(data) {
                t.html(data); 
           });	
		});
		
		var get_amazon_url = HTTP_SERVER + "includes/getAmazon.php"; 
		getAmazon = function(Keywords,SearchIndex, ItemPage, div, NumberOfItems, Operation) { 
			if(!Operation) Operation ='ItemSearch';  
			$.get(get_amazon_url, { Keywords: ""+Keywords+"", SearchIndex: ""+SearchIndex+"", ItemPage: ""+ItemPage+"", div: ""+div+"", NumberOfItems: ""+NumberOfItems+"", Operation: ""+Operation+"" },
			  function(data){
				$('#'+div).html(data);
			  });
		}
		
		

    
});
