/* 
 * Javascript für alle Seiten
 */

/* Cookie Functions */
function setCookie(name,value,expires) {
    var expireTime = new Date();
    expireTime = new Date(expireTime.getTime() + 1000*expires);
    document.cookie = name+'='+value+'; path=/; expires='+expireTime.toGMTString()+';';
}

function getCookie(n) {
    var c = document.cookie;
    while(c != '') {
        var name = c.substring(0,c.indexOf('=')).replace(' ','');
        var value = c.substring(c.indexOf('=')+1,c.length);
        if(value.indexOf(';') > -1) {
            value = value.substring(0,value.indexOf(';'));
        }
        if(name == n) return value;
        if(c.indexOf(';') != -1) {
            c = c.substring(c.indexOf(';')+1, c.length);
        } else {
            return '';
        }
    }
    return '';
}

function deleteCookie(name) {
	setCookie(name,'', -1000000);
}

function createShutter(id,opacity)
{

	$('#margin_wrapper').append('<div id="' + id + '" class="shutter"></div>');

	$("#" + id).css('opacity', 0);

	$("#" + id).css('z-index', 1000);

	$("#" + id).height($(document).height());

	$('#' + id).animate({
		opacity: opacity
	}, 400, function() {
	    // Animation complete.
	});

}

function removeShutter(id)
{
	$('#' + id).animate({
		opacity: 0
	}, 400, function() {
	    // Animation complete.
		$("#" + id).remove();
	});

}

function createDialogBox(id,width,height,shutterOpacity,callback)
{
        var viewportHeight = jQuery(window).height();

	var documentScrollTop = jQuery(document).scrollTop();

	var topPosition = documentScrollTop + viewportHeight/2 - height/2;

	createShutter(id + '_shutter',shutterOpacity);

	$('#margin_wrapper').append('<div id="' + id + '" class="dialog_box"></div>');

	$("#" + id).css('z-index', 1001);

	$("#" + id).css('display', 'none');

	$('#' + id).height(height);

	$('#' + id).width(width);

	$("#" + id).css('margin-left', '-' + (width/2) + 'px');

	$("#" + id).css('top', topPosition + 'px');

	/*$('#' + id).animate({
		opacity: 1
	}, 100, function() {
	    // Animation complete.
            callback.call();
	});*/
        $('#' + id).show();
        callback.call();

}

//Entfernt die Dialogbox
function removeDialogBox(id)
{

	$('#' + id).animate({
		opacity: 0
	}, 600, function() {
	    // Animation complete.
		$("#" + id).remove();
	});

	removeShutter(id + '_shutter');

}

function show_map(lat, lng) {
    createDialogBox('layer_map',700,500,0.3, function() {
        $('#layer_map').append('<img src="/img/button_close_big.gif" class="close" /><div id="result_map"></div>');
        $('#layer_map .close, #layer_map_shutter').click(function() {removeDialogBox('layer_map');});
        
            var latlng = new google.maps.LatLng(44.2, 15.55);
            var myOptions = {
                zoom: 7,
                center: latlng,
                disableDefaultUI: true,
                navigationControl: true,
                mapTypeControl: true,
                mapTypeId: google.maps.MapTypeId.TERRAIN
            };
            var map = new google.maps.Map(document.getElementById("result_map"), myOptions);
            var rentobj = new google.maps.LatLng(lat, lng);
            var marker = new google.maps.Marker({
                position: rentobj,
                map: map
            });
        
    });
        
}

function showBookingSchedule(objectID) {
    createDialogBox('booking_schedule',950,500,0.3, function() {
        $('#booking_schedule').append('<img src="/img/button_close_big.gif" class="close" /><div id="booking_schedule_content"></div>');
        $('#booking_schedule .close, #booking_schedule_shutter').click(function() {removeDialogBox('booking_schedule');});
        var timestamp = new Date().getTime();
        //switch range to 2 for showing booking schedule of next year, to 1 for showing actual year first
        $('#booking_schedule_content').load('/booking_schedule.html?oid='+objectID+'&range=1'+'&t='+timestamp);
    });

}

function updateBookingSchedule(objectID, range) {
    var timestamp = new Date().getTime();
    $('#booking_schedule_content').load('/booking_schedule.html?oid='+objectID+'&range='+range+'&t='+timestamp);
}



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

function initMenus() {
    $('ul.menu ul').hide();
    var parents = $('ul.menu').find('.act').parents('li');
    parents.find('ul:first').show();
    parents.find('a:first').addClass('act');
    $.each($('ul.menu'), function(){
        $('#' + this.id + '.expand ul:first').show();
    });
    $('ul.menu li a').click(
        function() {
            var checkElement = $(this).next();
            var root = $(this).parents('.menu').attr('id');

            var exception = $(this).parents('ul');
            $('#' + root + ' ul:visible').not(exception).slideUp({
                duration: 'fast'});

            if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
                checkElement.slideUp({
                    duration: 'fast',
                    callback: function() {return true;}
                });
            }
            if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
                checkElement.slideDown({
                    duration: 'fast',
                    callback: function() {return true;}
                });
            }
            return true;
        }
    );
    $('a[href="#"]').click(function() {return false;});
}

function slideShow(obj, speed, blendtime) {
    if (obj.length <=1) return;

    var fn = {
        loop: function() {
            fn.blend();
            setTimeout(fn.loop, speed);
        },
        blend: function() {
            var current = obj.filter('.current').fadeOut(blendtime).removeClass('current');
            current = (current.next().length) ? current.next() : obj.first();
            current.fadeIn(blendtime).addClass('current');
        }
    }

    obj.hide();
    obj.first().show();
    setTimeout(fn.loop, speed);
}

function initSlider() {
    var all = $('.slider .content');
    all.not('.open').hide();
    $('.slider h2').click(
        function() {
            var content = $(this).next();
            all.slideUp('fast').not('.open');
            $('.slider h2').css('background-image','url(/img/bakgrd_slider_arrow.gif)');
            $('.slider h2').css('background-position','16px 13px');
            if(content.is(':visible')) {
                content.slideUp('fast');
                $(this).css('background-image','url(/img/bakgrd_slider_arrow.gif)');
                $(this).css('background-position','16px 13px');
            }
            if(!content.is(':visible')) {
                content.slideDown('fast');
                $(this).css('background-image','url(/img/bakgrd_slider_arrow_open.gif)');
                $(this).css('background-position','15px 13px');
                
            }            
            return true;
        }
    );
}

function addObjectToRememberList(obj_id) {
    var con = confirm('Möchten Sie dieses Object zu Ihrer Merkliste hinzufügen? Dann bestätigen Sie bitte mit "OK"!\n Sie finden Ihre Merkliste unterhalb des Bereiches "Ansprechpartnerin"!');
    if (con) {        
        var remember_list = getCookie('remember_list');
        var remember_list_array = remember_list.split(',');
        if (remember_list == '' && remember_list_array.length < 10) {
            remember_list += obj_id;
            setCookie('remember_list',remember_list,60*60*24*400);
            location.reload();
        } else if(!in_array(obj_id,remember_list_array) && remember_list_array.length < 10) {
            remember_list += ',' + obj_id;
            setCookie('remember_list',remember_list,60*60*24*400);
            location.reload();       
        }
        
    }
}

function addObjectToRecentObjects(obj_id) {
    var recent_objects_list = getCookie('recent_objects_list');
    var recent_objects_list_array = recent_objects_list.split(',');
    if (recent_objects_list == '') {
        if (recent_objects_list_array.length == 10) recent_objects_list = recent_objects_list.substring(recent_objects_list.indexOf(',')+1);
        recent_objects_list += obj_id;
        setCookie('recent_objects_list',recent_objects_list,60*60*24*400);
    } else if(!in_array(obj_id,recent_objects_list_array)) {
        if (recent_objects_list_array.length == 10) recent_objects_list = recent_objects_list.substring(recent_objects_list.indexOf(',')+1);
        recent_objects_list += ',' + obj_id;
        setCookie('recent_objects_list',recent_objects_list,60*60*24*400);
    }
}

$(document).ready(function(){
    initSlider();
    initMenus();
    slideShow($('#slideshow img'), 5000, 1000);
    slideShow($('#offers .rent_obj'), 4000, 500);
    $('#rentobj #images a').lightBox({
        overlayBgColor: '#000',
        overlayOpacity: 0.5,
        imageLoading: '/img/lightbox-ico-loading.gif',
        imageBtnClose: '/img/lightbox-btn-close.gif',
        imageBtnPrev: '/img/lightbox-btn-prev.gif',
        imageBtnNext: '/img/lightbox-btn-next.gif',
        containerResizeSpeed: 350,
        txtImage: 'Bild',
        txtOf: 'von'
    });
    $('.more_pics').click(function() {
        $('#rentobj #images a:first').trigger('click');
    });
    $('a[rel]="newwindow"').attr('target', '_blank').attr('title', 'URL in neuem Fenster öffnen');
    $('#param_reg').change(function() {
        $('#param_loc option').removeAttr('selected');
    });
    $('#param_loc').change(function() {
        $('#param_reg option').removeAttr('selected');
    });
    $('#remember_me').click(function() {
        var obj_id = $(this).attr('name').substring(16);
        addObjectToRememberList(obj_id);
    });
    $('#col3 .arrow_down').click(function() {
        var pos = $(this).parent().find('.slider').position().top;
        var height = $(this).parent().find('.slider').height();
        pos -=50;
        if ( pos > (400-height)) $(this).parent().find('.slider').css('top', pos+'px');
    });
    $('#col3 .arrow_up').click(function() {
        var pos = $(this).parent().find('.slider').position().top;
        pos +=50;
        if ( pos < 1) $(this).parent().find('.slider').css('top', pos+'px');
    });
    $('#show_pos h2').click(function(){
       if ( $('#show_pos .content').is(':visible') ) {
           setTimeout(initialize(), 1000);
       }
    });
    jQuery(function($){
    $.datepicker.regional['de'] = {clearText: 'löschen', clearStatus: 'aktuelles Datum löschen',
            closeText: 'schließen', closeStatus: 'ohne Änderungen schließen',
            prevText: '&#x3c;zurück', prevStatus: 'letzten Monat zeigen',
            nextText: 'Vor&#x3e;', nextStatus: 'nächsten Monat zeigen',
            currentText: 'heute', currentStatus: '',
            monthNames: ['Januar','Februar','März','April','Mai','Juni',
            'Juli','August','September','Oktober','November','Dezember'],
            monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
            'Jul','Aug','Sep','Okt','Nov','Dez'],
            monthStatus: 'anderen Monat anzeigen', yearStatus: 'anderes Jahr anzeigen',
            weekHeader: 'Wo', weekStatus: 'Woche des Monats',
            dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
            dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
            dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
            dayStatus: 'Setze DD als ersten Wochentag', dateStatus: 'Wähle D, M d',
            dateFormat: 'dd.mm.yy', firstDay: 1,
            initStatus: 'Wähle ein Datum', isRTL: false};
    $.datepicker.setDefaults($.datepicker.regional['de']);
    });

    $("#toDate").datepicker({minDate: 0, maxDate: "+12M"});
    $("#fromDate").datepicker({
        minDate: 0, maxDate: "+12M",
        onSelect: function(dateText) {
                        var dateParts = dateText.split(".");
                        $("#toDate").datepicker( "option", "minDate", new Date(dateParts[2], dateParts[1]-1, dateParts[0]) );
        }
    });
    $("a[href^='http://']").attr('target', '_blank');
    $("a[href^='https://']").attr('target', '_blank');
    $("#references").append('<a href="http://www.bellnet.de/suchen/reisen/ferienwohnung/kroatien.html"><img src="/img/bellnet-top10.gif" alt="Bellnet TOP10" /></a>');
});
