$(document).ready(function(){
   if($.cookie('from')!='' && $.cookie('to')!=''){
       var to,from;
       to =$('#dateTo');from = $('#dateFrom');
       if(from.val()==''){from.val($.cookie('from'));}
       if(to.val()==''){to.val($.cookie('to'));}
       to = $('#to');from = $('#from');
       if(from.val()==''){from.val($.cookie('from'));}
       if(to.val()==''){to.val($.cookie('to'));}
   }
   if(is_listing()===true){
       if($.cookie("map_display")=='block'){
           $('#map').css('display','block');
           show_map('listing');
           $('a.showMap',$('#selection')).first().addClass('loaded');
           $('#zoom').css('display','none');
           $('span',$('a.showMap')).html('ausblenden \u25b2');
       }
   }
//smooth scrolling----------------------------------------
$('a[href*=#]').not('.dontScroll').bind("click", function(event) {
		event.preventDefault();
		var ziel = $(this).attr("href");

		$('html,body').animate({
			scrollTop: $(ziel).offset().top
		}, 2000 , function (){location.hash = ziel;});
});
//datepicker----------------------------------------
	$('.datepicker').datepicker({
		showOn: 'both',
		buttonImage: '/img/site/iconCal.png',
		altField: '#actualDate',
		buttonText: 'Kalender ' + unescape("%F6") + 'ffnen',
                buttonImageOnly: true,
		dateFormat: 'dd.mm.yy',
		changeMonth: true,
		changeYear: true,
		dayNamesMin: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
		firstDay: 1,
		monthNames: ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
		monthNamesShort: ['Jan','Feb','Mrz','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
		yearRange: '2011:2012',
		showAnim: 'fold',
		beforeShow: customRange
	});
        $('.datepickerNoButton').datepicker({

		dateFormat: 'dd.mm.yy',
		changeMonth: true,
		changeYear: true,
		dayNamesMin: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'],
		firstDay: 1,
		monthNames: ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
		monthNamesShort: ['Jan','Feb','Mrz','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
		yearRange: '2011:2012',
		showAnim: 'fold',
		beforeShow: customRange
	});

	function customRange(input) {
		if(input.id == "to") {
			return {minDate: $('#from').datepicker('getDate') ? new Date(new Date($('#from').datepicker('getDate')).getTime() + 86400000 *1) : new Date()}
		}
        if(input.id == "dateFrom") {
            return {minDate:new Date()}
        }
        if(input.id == "dateTo"){
            return {minDate: ($('#dateFrom').datepicker('getDate') ? new Date(new Date($('#dateFrom').datepicker('getDate')).getTime() + 86400000 *1) : new Date())}
        }
		else {
			return {minDate: new Date(new Date().getTime() + 86400000 *1)}
		}
	}


//------------ weitere Bilder ein/ausblenden---------------------------
var imgNumber = 14 // default img number
var imgCount = $('#detailsImgs').find('ul.imgBox').length;
if(imgCount > (imgNumber + 1 ))
{
        $('#detailsImgs').find('ul.imgBox:gt(' + imgNumber + ')').hide();
        $('a.slideDown').click(function(){

                $('#detailsImgs').find('ul.imgBox:gt(' + imgNumber + ')').slideDown(function(){

                        $('#detailsImgs a#switch').attr('class','slideUp').text('Weniger Bilder anzeigen ▲');
                        $('#detailsImgs a.slideUp').live('click', function(){

                                $('#detailsImgs').find('ul.imgBox:gt(' + imgNumber + ')').slideUp(function(){
        //                        $('#detailsImgs').find('ul.imgBox:gt(5)').hide(function(){
                                        $('#detailsImgs a#switch').attr('class','slideDown').text('Weitere Bilder anzeigen ▼');
        //                                $('html,body').animate({
        //                                     scrollTop: $('#detailsImgs') .offset().top
        //                                     }, 1000);

                                        });

                                });

                        });

                });
}
else
{
    $('div#detailsImgs').css('background-image','none');
    $('div#detailsImgs #switch').hide();

}
//------belegungsplan/map----------------

//ein/ausblenden-----------------------------
	$('.buttons a.trigger').click(function(){
		box = $(this).parent().parent().parent().parent().parent();
		$(box).addClass('current');
		$('div.object').not(box).removeClass('current');
		$('a.slideDown').live('click', function(){
			box = $(this).parent().parent().parent().parent();
			lastClick = $(this);
			$(lastClick).addClass('current')
			$(box).find('.container').slideDown(function(){
				$(box).find('.slideDown').removeClass('slideDown')
				$(lastClick).addClass('slideUp')
				});
			});
		$('a.slideUp').live('click', function(){
			box = $(this).parent().parent().parent().parent();
			trigger = $(this);
			$(this).removeClass('current');
			$(box).find('.container').slideUp(function(){
				$(box).find('.trigger').removeClass('slideUp').addClass('slideDown');
				});
			});
		});

//umschalten-------------------------------------------

	$('li.buttonLocal a').click(function(){
		box = $(this).parent().parent().parent().parent();
		$(this).addClass('current');
		$(box).find('li.buttonAvail a').removeClass('current');
		$(box).find('.slider').animate({
			left: "-612"
			}, 400, function(){
				$(box).find('li.buttonLocal a').addClass('slideUp')
				});
		$(box).find('li.buttonAvail a').removeClass('slideUp');
		});
	$('li.buttonAvail a').click(function(){
		box = $(this).parent().parent().parent().parent();
		$(this).addClass('current');
		$(box).find('li.buttonLocal a').removeClass('current');
		$(box).find('.slider').animate({
			left: "0"
			}, 400, function(){
				$(box).find('li.buttonAvail a').addClass('slideUp')
				});
		$(box).find('li.buttonLocal a').removeClass('slideUp');
		});



//belegungsplan - jahre umschalten ----------------------------
    $('div.bookCal',$('#content-inner')).each(function(){
        $this = $(this);
        var year_select = $('select.bc_year',$this);
        var house_select = $('select.bc_house',$this);
        var container = $('div.bookCal_container',$this);
        var year_name = $('span.bc_year_name',$this);
        var house_name = $('span.bc_house_name',$this);
        house_select.change(function(){load_booking_cal(house_select,year_select, container,house_name,year_name);});
        year_select.change(function(){load_booking_cal(house_select,year_select,container,house_name,year_name);});
    });
    // Detail:Trigger change event on load
    $('#bc_detail_year').trigger('change');
    // trigger change event once when booking cal tab is opened
    $('.bc_trigger',$('#content-inner')).each( function(){
        $(this).one('click',function(){$('.bc_year',$(this).parent().parent().parent().parent()).trigger('change');});
    });

    $('.map_trigger',$('#content-inner')).each( function(){
        $(this).one('click',function(){
            container = $('.map-inner',$(this).parent().parent().parent().parent().parent().find('.map'));
            loadmap( this.id.substr(4) , container.get(0) );
        })
    });
    $('.bc_house').each(function(){if(this.options.length <= 1){$(this).hide()}});
    /*
	$('#year option[value=2011]').attr('selected', true);

	$('.nextYear').hide();
	$('.currentYear').show();
	$('.selectedYear').html(2011);

	$('.year').change(function(){
		var cal = $(this).parent().parent()

		if ($(this).val()==2012) {
			$(cal).find('.nextYear').show();
			$(cal).find('.currentYear').hide();
		    $(cal).find('.selectedYear').html(2012);
		}
		else {
			$(cal).find('.nextYear').hide();
			$(cal).find('.currentYear').show();
			$(cal).find('.selectedYear').html(2011);
		}

	});
    */
   //$('#year,#obj_houses_select').change(function(){ booking_cal();}).first().trigger('change');
//fancybox-------------------------------------------------------------------

$('a.lightbox').fancybox({
		overlayOpacity		:	0,
		hideOnOverlayClick	:	true,
		transitionIn		: 	"elastic",
		transitionOut		:	"elastic",
                titlePosition 		:       "inside"

		});

//Zeitraumsuche umschalten----------------------------------------------------------------



$('#flexible input').live("click", function(){
            $('#periodDuration select').removeAttr("disabled");
			});
$('#fixed input').live("click", function(){
            $('#periodDuration select').attr('disabled','disabled');
            });



//Startseite - Maps highlighten----------------------------------------------------------------

$('#frontIslands a').mouseleave(function(){
    $('#canariesMap, #balearicsMap').css({
        'background-position':'center 0px'
});
    $(this).removeClass('current');
	});
$('#frontIslands a').mouseover(function(){
    $(this).addClass('current');
    $('#frontIslands:has(ul li a.elHierro.current) #canariesMap').css('background-position','center -200px');
    $('#frontIslands:has(ul li a.laPalma.current) #canariesMap').css('background-position','center -400px');
    $('#frontIslands:has(ul li a.laGomera.current) #canariesMap').css('background-position','center -600px');
    $('#frontIslands:has(ul li a.teneriffa.current) #canariesMap').css('background-position','center -800px');
    $('#frontIslands:has(ul li a.granCanaria.current) #canariesMap').css('background-position','center -1000px');
    $('#frontIslands:has(ul li a.fuerteventura.current) #canariesMap').css('background-position','center -1200px');
    $('#frontIslands:has(ul li a.lanzarote.current) #canariesMap').css('background-position','center -1400px');
    $('#frontIslands:has(ul li a.laGraciosa.current) #canariesMap').css('background-position','center -1600px');

    $('#frontIslands:has(ul li a.mallorca.current) #balearicsMap').css('background-position','center -140px');
    $('#frontIslands:has(ul li a.ibiza.current) #balearicsMap').css('background-position','center -280px');
    $('#frontIslands:has(ul li a.menorca.current) #balearicsMap').css('background-position','center -420px');
});


//-------expand request form-------------------------------------------
var bookingText = 'Bitte senden Sie uns Ihre Reisedaten für Ihre verbindliche Buchung! Wir lassen Ihnen umgehend alle Buchungsunterlagen zukommen.';
var requestText = 'Bitte senden Sie uns eine unverbindliche Anfrage mit Ihren Reisedaten und offenen Fragen zu, wir setzen uns umgehend mit Ihnen in Verbindung.';
$('#reqOptions input:checked').siblings('label').addClass('bold');
$('#reqOptions input#nonBind').attr('checked',true).siblings('label').addClass('bold');
$('#reqOptions input#bind').siblings('label').removeClass('bold')
if ($('#reqOptions input:checked').attr('id') == 'nonBind')
    {
        $('#expandForm').text('Weiter zur Anfrage');
        $('#request .formInfo').text(requestText);
        $('#request h4 span.requestType').text('Unverbindliche Anfrage für ');
        $('#requestSubmit').val('Unverbindliche Anfrage senden!');
    }
else
    {
        $('#expandForm').text('Weiter zur Buchung');
        $('#request .formInfo').text(bookingText);
        $('#request h4 span.requestType').text('Verbindliche Buchung für ');
        $('#requestSubmit').val('Jetzt buchen!');
    }

$('#reqOptions input').change(function()
        {
                $('#reqOptions input').siblings('label').toggleClass('bold')
                if ($('#reqOptions input:checked').attr('id') == 'nonBind')
                {
                    $('.bind').slideUp();
                    $('.nonBind').slideDown();
                    $('input#agb, input#liability').attr('checked',false);
                    $('#requestSubmit').val('Unverbindliche Anfrage senden!');
                    $('#request h4 span.requestType').text('Unverbindliche Anfrage für ');
                    $('#request .formInfo').text(requestText);
                    $('#expandForm').text('Weiter zur Anfrage');
                }
                else
                {
                    $('.bind').slideDown();
                    $('.nonBind').slideUp();
                    $('#requestSubmit').val('Jetzt buchen!');
                    $('#request h4 span.requestType').text('Verbindliche Buchung für ');
                    $('#request .formInfo').text(bookingText);
                    $('#expandForm').text('Weiter zur Buchung');
                }
        });
$('#expandForm').click(function(){
        if( $(this).hasClass('button-disabled')===true){return;}
        if ($('#reqOptions input:checked').attr('id') == 'nonBind')
                {
                    $('.bind').hide();
                    $('.nonBind').show();

                }
                else
                {
                    $('.bind').show();
                    $('.nonBind').hide();

                }


        $('#requestBlock2').slideDown(function (){
            $('#requestSubmit').show();
            $('#expandForm').hide();
            $('html,body').animate({
			scrollTop: $('#requestBlock2') .offset().top
			}, 1000);

            });
    });

//-------show listing map-------------------------------------------
$('a.showMap').click(function(){
    var el = $('span',$('a.showMap'));
    if(this.id.substr(0,4)=='map_'){mode='detail';}else{mode='listing';}
    $('#map').slideToggle(400,function(){
        if($(this).css('display')=='block'){
            $.cookie("map_display",'block',{path: '/'});
            el.html('ausblenden \u25b2');
            if($(this).hasClass('loaded')==false){show_map(mode);$(this).addClass('loaded');}
        }else{
            el.html('anzeigen \u25bc');
            $.cookie("map_display",'none',{path: '/'});
        }
    });
    $('#zoom').fadeToggle(400,function(){});
    return false;
});
$('a#hideMap').click(function(){
    $('#map').slideUp();
    $('#zoom').fadeIn();
    $('span',$('a.showMap')).html('anzeigen \u25bc');
    $.cookie("map_display",'none',{path: '/'});
    return false;
});

    $('#map_detail_switch').click(function(){
        var text = $(this).text();
        var text_1 = 'Detailansicht (Satellit)';
        var text_2 = 'Kartenansicht';
        container = $('div.map_container',$('#map'));
        id = $('a.showMap').get(0).id.substr(4);
        if( text == text_1){
            $(this).text(text_2);
            zoom=17;type=google.maps.MapTypeId.SATELLITE;center=true;
        }else{
            $(this).text(text_1);
            zoom=null;type=null;center=null;
        }
        loadmap( id , container.get(0) , zoom , type , center ,'detail');
    });
//--------------show nav map tooltip-----------------------------------------

$.fn.tooltip = function(optionen){
        optionen = $.extend({
        hintergrund: "#fff",
        schriftfarbe: "#000",
        rand: "2px #ABABAB solid",
        eckenradius: 10,
        zeit: 1000
        }, optionen);

    function zeigeTooltip(evt, zeit, content){
        $("<div>", {
//          id: "tooltip",
            css: {
                position: "absolute"



//                padding: "10px",
////                background: optionen.hintergrund,
//                color: optionen.schriftfarbe,
//                fontFamily: "Tahoma, Helvetica, sans-serif",
//                fontSize: "12px",
//                border: optionen.rand,
//                display: "none",
//                "-moz-border-radius": optionen.eckenradius,
//                "-webkit-border-radius": optionen.eckenradius
                },
            html: content
            })
        .addClass('tooltip')
        .appendTo("body")


        }

        $(this).each(function(){
        var that    = $(this);
        var imgName = $(this).attr("title");
        var content = "<img src='/img/maps/small/" + imgName + ".gif'/>"
        var offset  = $(this).offset();
        var offsetLeft    = offset.left -105;
        var offsetTop    = offset.top;
        $(window).resize(function(){
            offsetLeft   = that.offset().left -105;
            offsetTop    = that.offset().top;
                      });
        $(this).attr('title','');


        $(this).bind({
            mouseenter: function(evt){
                if ($(".tooltip").css("opacity") != 0) {
                 $(".tooltip").stop().remove();

                 //alert(left +'; ' + top)
                }

            zeigeTooltip(evt, optionen.zeit, content);
            $(".tooltip").css('left', offsetLeft);
            $(".tooltip").css('top', offsetTop);
//            $(".tooltip").animate({
//                    left: offsetLeft
//                })
            },
            mouseleave: function(){
                $(".tooltip").animate({
                    left: offset.left
                },
                optionen.zeit,
                function(){
                    $(this).remove();
                    }
                );
            }

//            mousemove: function(evt){
//                $(".tooltip").css({
//                    left: 20,
//                    top: evt.pageY + 20
//                    });
//                }
        });
    });
}

// call
$("#navi #islandNav li ul li a").tooltip({

});
//----------- open carInfo-popup ------------------------

//$('a#carInfo').click(function(){
//    window.open('/mietwagen-info.html','Informationen zu Mietwagen auf den Kanaren','width=800, height=600, scrollbars=yes, left=200, top=100');
//    });
$('a#carInfo').click(function(event){
    event.preventDefault();
    var win = window.open($(this).attr('href'),$(this).attr('target'),'width=800,height=600,scrollbars=yes,left=200,top=110,toolbar=no,location=no,menubar=no');
    win.focus();
});
$('#rental_car_link').click(function(event){
    event.preventDefault();
    var win = window.open($(this).attr('href'),$(this).attr('target'),'width=800,height=600,scrollbars=yes,left=200,top=110,toolbar=no,location=no,menubar=no');
    win.focus();
});

//----------fontsize tagCloud------------------

//var t=0;
//var t_elem;
//var maxFontSize = 24;
//$("ul#tagCloud li a").each(function () {
//    $this = $(this);
//    if ( $this.attr('rel') >= t )
//        { t_elem=this; t=$this.attr('rel'); }
//    var s = $(this).attr('rel');
//    var test = (maxFontSize / t);
//    var fontSize = (maxFontSize / t) * s;
//    //alert(fontSize)
//    $(this).css({
//        'font-size': fontSize + 10 + 'px',
//        'margin-right': fontSize + 10 + 'px'
//    });
//
//
//});

//--------------accordion-----------------

$('.accordion .expandMe').hide();
$('.accordion .trigger').live('click', function(){
    $(this).siblings('.expandMe').slideDown(function(){
        $(this).removeClass('expandMe').addClass('collapseMe');
    });
    $(this).siblings('.collapseMe').slideUp(function(){
        $(this).removeClass('collapseMe').addClass('expandMe');

    });
    return false;
});

//--------------dropShadow für IE---------------------------
//function getInternetExplorerVersion()
//// Returns the version of Internet Explorer or a -1
//// (indicating the use of another browser).
//{
//  var rv = false; // Return value assumes failure.
//  if (navigator.appName == 'Microsoft Internet Explorer')
//  {
//    var ua = navigator.userAgent;
//    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
//    if (re.exec(ua) != null)
//      rv = parseFloat( RegExp.$1 );
//  }
//  return rv;
//}
//var vers = getInternetExplorerVersion();
//var name = navigator.appName;
//
//
//
//if (name == "Microsoft Internet Explorer" && vers < 9){
//
//
//     $(".button").filter(':visible').not('.button.current').dropShadow({
//        left:3,
//        top:3,
//        opacity: 0.3,
//        color: "#000000"
//    });
//    $("#nav").dropShadow({
//        left:0,
//        top:3,
//        opacity: 0.3,
//        color: "#000000"
//    });
//
//    }
//--------------listing - show house table------------------
$('.object').each(function(){
    var trigger = $(this).find('.open_house_table');
    var houseTable = $(this).find('.house_table_wrapper');
    trigger.click(function(){
        houseTable.slideToggle();
//        $('table.house_table').not(houseTable).hide();
    });


});

//----------------------------------------------------------


   $('input.radio',$('#units')).click( function(){
        var sel = $('#pers',$('#priceBuilder'));
        $.ajax('/xhr/max_persons_options/'+this.value+'/',{
            'dataType':'json',
            success:function( response ){
                sel.loadSelect(response.options);
                sel.val(response.normal);
                sel.attr('normal',response.normal);
                sel.trigger('change');
            },
            error:function(){sel.parent().addClass('loading');}
        });
    })

    var priceBuilderDefault = 'Bitte geben Sie<br>An- und Abreisedatum ein.'
    $('#priceTop').html(priceBuilderDefault);
//    if($('#priceTop').html()== priceBuilderDefault)
//    {
//        $('#requestSubmit').addClass('button-disabled');
//    }
    $('input.radio:checked',$('#units')).trigger('click');
    $('input,select',$('#priceBuilder')).change(function(){
        dateFrom = $.trim($('#dateFrom',priceBuilder).val());
        dateTo = $.trim($('#dateTo',priceBuilder).val());
        if( dateFrom == '' || dateTo == ''){
            $('#priceTop').html(priceBuilderDefault);
            $('#priceBoxContent').removeClass('loading');
            $('#priceValue').html('');
            $('#priceBottom').html('');
            $('#priceBoxBottom').removeClass('free allocated').html('&nbsp;');
//            $('#requestSubmit').addClass('button-disabled');
        } else {
            var priceBuilder = $('#priceBuilder');
            var postdata = {
                "haus" : $('input:checked',$('#units')).val(),
                "from" : dateFrom,
                "to" : dateTo,
                "no_persons" : $('option:selected',$('#pers',priceBuilder)).val(),
                "car" : $('#carOpt').val(),
                "island_id" : $('#island_id').val()
            };
            $.ajax('/xhr/price_builder/',{
                type:'post',
                data:postdata,
                dataType:'json',
                beforeSend:function(){
                    $('#priceBoxContent').addClass('loading');
                    $('#priceTop').html('Preis wird berechnet.');
                    $('#priceValue').html('&nbsp;');
                    $('#priceBottom').html('&nbsp;');
                },
                success:function(response){
                    $('#priceBoxContent').removeClass('loading');
                    $priceBuilder = $('#priceBuilder');
                    if(response.duration <=0){
                        $('#priceTop').html('Bitte geben Sie ein g' + unescape('%FC') + 'ltiges<br>An- und Abreisedatum ein.');
                        $('#priceValue').html('');
                        $('#priceBottom').html('');
                        $('#priceBoxBottom').removeClass('free allocated').html('&nbsp;');
                        $('#expandForm,#requestSubmit').addClass('button-disabled');
                        $('#price_house,#price_car,#price_details').val('');
                    }else{
                        $.cookie("to",response.to,{expires:3,path: '/'});
                        $.cookie("from",response.from,{expires:3,path: '/'});
                        $('#priceTop',$priceBuilder).html(response.duration+' Nächte / '+response.pers+' Pers.');
                        $('#priceValue',$priceBuilder).html(response.price);
                        $('#price_numeric').val(response.price_numeric);
                        $('#rq_duration').val(response.duration);
                        $('#price_details').val(response.details_string);
                        $('#price_house').val(response.price_house);
                        $('#price_car').val(response.price_car);
                        var texte = ['buchbar','Auf Anfrage','belegt','belegt',''];
                        $('#house_status_id').val(response.house_status);
                        $('#priceBottom',$priceBuilder).html(response.car!="nein"?'inkl. Mietwagen':'&nbsp;');
                        if( response.rental_car_link != false){$('#rental_car_link').attr('href',response.rental_car_link.replace(/amp;/g,''));}
                        if(response.bookable == true){
                            $('#priceBoxBottom',$priceBuilder).text(texte[response.house_status]).removeClass('allocated').addClass('free');
                            $('#expandForm,#requestSubmit').removeClass('button-disabled');
                        }else{
                            $('#priceBoxBottom',$priceBuilder).text(texte[response.house_status]).removeClass('free').addClass('allocated');
                            $('#expandForm,#requestSubmit').addClass('button-disabled');
                        }
                    }
                }
            });
        }
    });
    $('#pers').change(function(){
        var count_new = $(this).val();
        var count_old = $('ul.pers').size();
        var html = '';
        if( count_new > count_old ) {
            for(k=count_old;k<count_new;k++){
                html+= '<ul class="pers" id="ul_pers'+k+'">';
                html+= '<li class="label">Person '+(k+1)+'</li>';
                html+= '<li class="textField"><input id="persLastName_'+k+'" name="persName['+k+'][LN]" type="text" /></li>';
                html+= '<li class="textField last"><input id="persFirstName_'+k+'" name="persName['+k+'][FN]" type="text" /></li>';
                html+= '</ul>';
            }
            $('#personsListItems').append(html);
        }else{
            for(k=count_old-1;k<=count_new;k++){$('#ul_pers'+k).hide();}
        }
        for(k=0;k<count_new;k++){$('#ul_pers'+k).show();}
        for(k=count_new;k<20;k++){$('#ul_pers'+k).hide();}
    });
   //forms
   contactForm.init();requestForm.init();
   load_pricetable($('#object_id').val(),2012);
   //$('body').prepend('<div>'+$.cookie('merkzettel')+'<div>');
   merkzettel.init();
   price_totals();
//---------------------------------------------------------------------------
});

requestForm = {
    errorMessage:'Ihre Anfrage konnte nicht gesendet werden! Bitte f' + unescape('%FC') + 'llen Sie alle mit "*" gekennzeichnete Felder aus.'
    ,successMessage:'Vielen Dank f' + unescape('%FC') + 'r Ihre Anfrage! Wir werden uns in K' + unescape('%FC') + 'rze mit Ihnen in Verbindung setzen.'
    ,init:function(){
        $priceBuilder = $('#priceBuilder');
        $('#requestSubmit').click(function(){

            if($(this).hasClass('button-disabled')){return;}
            var persons = [];
            $(':input[name*="persName"]').each(function(i){
                var name = $(this).attr('name');
                n = parseInt(name.replace (/[^\d]/g, ""));
                if(!persons[n]){persons[n]={first:"",last:""};}
                type = name.slice(name.length-3,name.length-1);
                if(type=="LN"){persons[n].last=$(this).val();}
                else{persons[n].first=$(this).val();}
            });
            requestForm.formdata = {
                title:$('#title').val(),
                email:$('#email').val(),
                firstName:$('#firstName').val(),
                phone:$('#phone').val(),
                lastName:$('#lastName').val(),
                fax:$('#fax').val(),
                address:$('#address').val(),
                city:$('#city').val(),
                message:$('#message').val(),
                dateFrom:$('#dateFrom').val(),
                dateTo:$('#dateTo').val(),
                pers:$('#pers').val(),
                unit:$(':input[name=unit]:checked',$('#requestForm')).val(),
                car:$('#carOpt').val(),
                binding:$(':input[name=reqOptions]:checked',$('#requestForm')).val(),
                /*insurance:$(':input[name=insurOptions]:checked',$('#requestForm')).val(),*/
                insurance:($('#insur:checked').size()>0?"ja":"nein"),
                liability:($('#liability:checked').size()>0),
                agb:($('#agb:checked').size()>0),
                persons:persons,
                free:$('#priceBoxBottom').hasClass('free'),
                calculated_price:$('#price_numeric').val(),
                calculated_days:$('#rq_duration').val(),
                price_details:$('#price_details').val(),
                price_house:$('#price_house').val(),
                price_car:$('#price_car').val(),
                car_detail:$('#carOpt option:selected').text(),
                house_status:$('#priceBoxBottom',$priceBuilder).text(),
                house_status_id:$('#house_status_id').val()
            }
            $.ajax('/xhr/requestForm/',{data:requestForm.formdata,type:'POST',dataType:'json',
                beforeSend:function(){ },
                success:function(response){requestForm.handleResponse( response );},
                error:function(xhr){requestForm.handleError()}
            });
        })
    }
    ,clearForm:function(){
        $('#email').val('');$('#firstName').val('');$('#phone').val('');$('#lastName').val('');
        $('#fax').val('');$('#address').val('');$('#city').val('');$('#message').val('');
        sel=$('#pers');sel.val(sel.attr('normal')).trigger('change');
        $('#agb').removeAttr('checked');$('#liability').removeAttr('checked');
        $('#insur').removeAttr('checked');
        $(':input[name*="persName"]').each(function(i){$(this).val('');});
    }
    ,handleResponse:function(o){
        $.each(o.types,function(key,value ){
            if(value==true){$('#'+key).parent().removeClass('error');}
            else{$('#'+key).parent().addClass('error');}
        });
        if(o.error==false){
            $('#requestBottomInfo').html(requestForm.successMessage+"").show();
            $('#requestBottomError,#requestTopError').html('').hide();
            if($(':input[name=reqOptions]:checked',$('#requestForm')).val()=='ja'){s = '/conversions/booking';}else{s = '/conversions/request';}
            try {
                _gaq.push(['_trackPageview', s]);
            } catch(err) {}
            //intelli ad
            var ia_tp="t23.intelliad.de/tc2.js";
            var ia_v="80.00"; // conversion value (i.e. "2.5") [mandatory]
            var ia_vz="le"; // conversion type (possible values: sale -> "sa", lead -> "le", signup -> "si", pageview -> "pa", download -> "do") [mandatory]
            var ia_vv="EUR"; // conversion currency code(ACCORDING ISO 4271 i.e. "EUR" or "USD") [optional,if not given "EUR" is used as default]
            var ia_po=""; // orderId [optional]
            var ia_sh=""; // user age [optional]
            var ia_nf=""; // user birth date (format: YYYYMMDD) [optional]
            var ia_hr=""; // user gender (possible values: "m" or "w") [optional]
            var ia_uo=""; // user zip code (5 digit zip code, i.e. "12345") [optional]
            var ia_vo=""; // user city (i.e. "Berlin") [optional]
            var ia_tr=""; // user region (i.e. "Bayern") [optional]
            var ia_vp=""; // user country (possible values: 2 char coutry code, i.e. "de")[optional]
            var ia_c1=""; // custom value 1 [optional]
            var ia_c2=""; // custom value 2 [optional]
            var ia_c3=""; // custom value 3 [optional]
            var ia_c4=""; // custom value 4 [optional]
            var ia_pi=""; // productIds (if more than 1 seperate with | e.g. "12356|56899") [optional]

            var ia_cl="2363932333236323131303";
            var ia_rand = Math.floor(Math.random()*11111139435231);

            var ia_link=ia_tp+'?cl='+ia_cl+'&v='+ia_v+'&vz='+ia_vz+'&vv='+ia_vv+'&po='+ia_po+'&sh='+ia_sh+'&nf='+ia_nf+'&hr='+ia_hr+'&uo='+ia_uo+'&vo='+escape(ia_vo)+'&tr='+escape(ia_tr)+'&vp='+ia_vp+'&c1='+ia_c1+'&c2='+ia_c2+'&c3='+ia_c3+'&c4='+ia_c4+'&pi'+ia_pi+'&rand='+ia_rand;
            $('#requestBottomInfo').append('<sc'+'ript src="'+'http'+(document.location.protocol=='https:'?'s':'')+'://'+ia_link+'"></sc'+'ript>');
            requestForm.clearForm();
        }else{
            $('#requestBottomError,#requestTopError').html(requestForm.errorMessage+'').show();
            $('#requestBottomInfo').html('').hide();
        }
    }
    ,beforeSend:function(xhr){return true;}
    ,handleError:function(){}
}

contactForm = {
    errorMessage:'Ihre Anfrage konnte nicht gesendet werden! Bitte f' + unescape('%FC') + 'llen Sie alle mit "*" gekennzeichnete Felder aus.'
    ,successMessage:'Vielen Dank f' + unescape('%FC') + 'r Ihre Anfrage! Wir werden uns in K' + unescape('%FC') + 'rze mit Ihnen in Verbindung setzen.'
    ,init:function(){
        $('#contactSubmit').click(function(){
            var formdata = {message:$('#message').val(),name:$('#name').val(),email:$('#email').val(),phone:$('#phone').val()};
            $.ajax('/xhr/contactForm/',{data:formdata,type:'POST',dataType:'json',
                beforeSend:function(){contactForm.beforeSend()},
                success:function(ret){contactForm.handleFormError( ret );},
                error:function(){contactForm.handleError()}
            });
        })
    }
    ,clearForm:function(){$('#message').val('');$('#name').val('');$('#email').val('');$('#phone').val('');}
    ,handleFormError:function(o){
        $.each(o.types,function(key,value ){
            if(value==true){$('#'+key).parent().removeClass('error');}
            else{$('#'+key).parent().addClass('error');}
        });
        if(o.error===false){
            contactForm.showSuccessMessage(o.send_error);
            $('#contactFormInfo').html('').hide();
            try {
                _gaq.push(['_trackPageview','/conversions/contact']);
            } catch(err) {}
            contactForm.clearForm();}
        else{$('#contactFormInfo').html(''+contactForm.errorMessage+'').show();}
    }
    ,showSuccessMessage:function( ok ){$('#contactFormMessage').html(''+contactForm.successMessage+'').show();}
    ,handleError:function(){}
    ,beforeSend:function(){}
};

//$(window).unload(function(){$.cookie("map_display",$('#map').css('display'),{path: '/'});});
var merkzettel = function(){
    this.data = [];
    this.setData = function( x ){this.data = x;};
    this.persist = function(){
        $.cookie('merkzettel',$.unique(this.data).join(','),{"path":"/","expires":14});
    }
    this.removeBookmark = function(id){
        this.data = $.grep(this.data, function(value) {return value != id;});
        this.persist();
    };
    this.hasElement = function( el ){return ( $.inArray(el,this.data) >=0 );};
    this.bookmarkLink = function(){
        if( $('#bookmarks').size() > 0 ){
            if(this.data.length > 0 ){
                $('li:first span',$('#bookmarks')).text('('+this.data.length+')').addClass('hasBookmarks');
            } else {
                $('li:first span',$('#bookmarks')).text('').removeClass('hasBookmarks');
            }
        }
    };
    return {
        init:function(){
            var self = this;
            if($.cookie('merkzettel')){self.setData($.cookie('merkzettel').split(','));}else{self.setData(new Array());}
            self.bookmarkLink();
            $('#bookmarks li:first a').click(function(){_gaq.push(['_trackEvent', 'favorites', 'show', 'header']);});
            // merkzettel
            if( $('#bookmark_container').size() > 0 ){
                $('div.object').each(function(){
                    var id = this.id.substr(4);
                    $(this).find('.object-inner').prepend('<ul class="pin"><li><a class="remove" title="Vom Merkzettel entfernen" href="javascript:;"></a></li><li class="shadow"></li></ul>');
                    $('a.remove',$(this).find('.object-inner')).click(function(){
                        self.removeBookmark(id);
                        _gaq.push(['_trackEvent', 'favorites', 'delete']);
                        location.reload();
                    });
                });
            }
            // Normales listing
            if($('#selection').size() > 0 ){
                $('div.object').each(function(){
                    if(self.hasElement(this.id.substr(4)) === true){
                        $(this).addClass('bookmarked');
                        $(this).find('.object-inner').prepend('<ul class="pin"><li><a href="/merkzettel" onClick="_gaq.push([\'_trackEvent\', \'favorites\', \'show\', \'listing\']);" title="Zum Merkzettel"></a></li><li class="shadow"></li></ul>');
                    }
                });
            }

            $('a.bookmarkThis').each(function(){
                id=this.id.substr(6);
                if(self.hasElement(id)===true){
                    $(this).addClass('bookmarked').attr('href','/merkzettel').attr('title','Merkzettel ansehen');
                    $('span.text',$(this)).text('Zum Merkzettel hinzugefügt');
                    $(this).click(function(){_gaq.push(['_trackEvent', 'favorites', 'show', 'detail']);});
                }else{
                    $(this).removeClass('bookmarked').attr('title','Auf den Merkzettel');
                    $('span.text',$(this)).text('Auf den Merkzettel');
                    $(this).one('click',function(){
                        self.data.push(id);
                        self.persist();
                        $this = $(this);
                        _gaq.push(['_trackEvent', 'favorites', 'add']);
                        $this.addClass('loading');
                        setTimeout(function(){
                            self.bookmarkLink();
                            $this.removeClass('loading').addClass('bookmarked').attr('title','Merkzettel ansehen').click(function(){
                                _gaq.push(['_trackEvent', 'favorites', 'show', 'detail']);
                                window.location='/merkzettel';
                            });
                            $('span.text',$this).text('Zum Merkzettel hinzugefügt');
                        },2000);
                    });
                }
            });
        },
        setData:setData,hasElement:hasElement,data:data,persist:persist,
        bookmarkLink:bookmarkLink,removeBookmark:removeBookmark
    }
}();

function show_map( mode ){
    container = $('div.map_container',$('#map'));
    if(mode=='detail'){
        id = $('a.showMap').get(0).id.substr(4);
        loadmap(id,container.get(0),null,null,null,'detail');
    } else {
        var infoWindow = new google.maps.InfoWindow;
        url = '/xhr/geodata_many/'+$('#h_gmap_type').val()+'/';
        $.ajax( url ,{
            dataType:'json',
            type:'post',
            data:{'ids':$('#h_item_ids').val()},
            success:function( response ){
                var map = new google.maps.Map(container.get(0),{
                    center:new google.maps.LatLng(response.meta.lat,response.meta.lng),
                    zoom:response.meta.zoom,
                    navigationControl: true,
                    scaleControl: false,
                    mapTypeControl: true,
                    mapTypeId: 'roadmap'
                });
                for (var i = 0; i < response.markers.length; i++) {
                    var point = new google.maps.LatLng(
                        parseFloat(response.markers[i].lat),
                        parseFloat(response.markers[i].lng)
                    );
                    var html = '';
                    var icon;
                    if( response.markers[i].typ == 'city'){
                        m_title = response.markers[i].name;
                        icon = 'brown_markerA.png';
                        icon = 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png';
                        tpl = $('#h_city_url_tpl').val();
                        url = tpl.replace(/#city#/,response.markers[i].url);
                        url = url.replace(/insel\/alle/,'insel/'+response.markers[i].island_key);
                        html+= '<div class="gmap_info"><a href="/'+url+'"><strong>&quot;'+response.markers[i].name+'&quot;</strong></a>';
                        html+= '<br><a href="/'+url+'">'+response.markers[i].count+' Objekt'+(response.markers[i].count>1?'e':'')+'&nbsp;&raquo;</a>';
                        html+= '</div>';
                    }else {
                        icon = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png';
                        m_title = response.markers[i].typ+' '+response.markers[i].name;
                        html+= '<div class="gmap_info"><a href="'+response.markers[i].url+'"><strong>'+response.markers[i].typ+'&nbsp;&quot;'+response.markers[i].name+'&quot;</strong></a>';
                        html+= '<br><a href="'+response.markers[i].url+'">Zur Detailansicht&nbsp;&raquo;</a>';
                        html+= '</div>';
                    }
                    var marker = new google.maps.Marker({
                        map: map,
                        position: point,
                        title: m_title,
                        icon:icon
                    });
                    bindInfoWindow(marker, map, infoWindow, html);
                }
            },
            error:function(){}
        });
    }
}

function bindInfoWindow(marker, map, infoWindow, html) {
    google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
    });
}

function load_booking_cal(house_select,year_select,container,house_name,year_name){
    var house = $(':selected',house_select)[0].value;
    var year = $(':selected',year_select)[0].value;
    house_name.html($(':selected',house_select)[0].text);
    year_name.html(year);
    $.ajax('/xhr/belegungsplan/'+house+'/'+year,{
        beforeSend:function(){
            container.prepend('<div class="loading"><div class="load_indicator">Laden</div></div>');
            $('table.bookTable td',container).each(function(){$(this).removeClass('inq allocated free arrdep')});
        },
        success:function(o){container.html(o);}
    });
}

function loadmap( id , container , zoom , type , center , mode ){
    $.ajax('/xhr/geodata2/'+id+'/',{
        dataType:'json',
        success:function( response ){
            if(zoom){use_zoom = zoom}else{use_zoom = response.meta.zoom;}
            if(type){use_type = type;}else{use_type = 'roadmap';}
            center_lat = parseFloat(response.meta.lat);
            center_lng = parseFloat(response.meta.lng);
            if(center){
                if(response.markers.length==1){
                    center_lat = parseFloat(response.markers[0].lat);
                    center_lng = response.markers[0].lng;
                }
            }
            var map = new google.maps.Map(container,{
                center:new google.maps.LatLng(center_lat,center_lng),
                zoom:use_zoom,
                navigationControl: true,
                scaleControl: false,
                mapTypeControl: true,
                mapTypeId: use_type
            });
            for (var i = 0; i < response.markers.length; i++) {
                var point = new google.maps.LatLng(
                    parseFloat(response.markers[i].lat),
                    parseFloat(response.markers[i].lng)
                );
                var marker = new google.maps.Marker({
                    map: map,
                    position: point
                });
            }
            if(!mode){$('div.map_note div.c66l',$(container).parent()).html('<div>'+response.message+'</div>');}
            else{if(response.has_geodata==false){$('div.map_note div.c66l',$(container).parent()).html(''+response.message+'');}}
        }
    });
}

function is_listing(){return ($('#selection').size() > 0);}

function load_pricetable( id , year ){
    if(id){
    $.ajax('/xhr/pricetable/'+id+'/'+year,{
        beforeSend:function(){$('#detailsPrice .price_container').html('&nbsp;').addClass('loading');}
        ,success:function(response){$('#detailsPrice .price_container').removeClass('loading').html(response);$('div.legend span',$('#detailsPrice')).html(year);}
    });}
}

function price_totals(){
   var search_params = get_period_search_params();
   if(search_params==false){ return; }
   var search_params_arr = search_params.split('_');
   var from,to,fixflex,dur=5;
   if(search_params_arr.length>2){
       from_to_arr = search_params_arr[0].split('-');
       if(from_to_arr.length==2){
           from = $.trim(from_to_arr[0]);
           to = $.trim(from_to_arr[1]);
       } else {
           return;
       }
       fixflex = search_params_arr[1];
       if(search_params_arr.length===3){
           dur_arr = search_params_arr[2].split('-');
           dur = dur_arr[0];
       }
   } else {
       return;
   }
   $('div.object',$('#content')).each(function(){
       $this = $(this);
       var house = $('.bc_house',$this).val();
       update_price_box($this,house,from,to,fixflex,dur);
   })
}

function get_period_search_params(){
    var x = $('input[name="search_params"]',$('#periodSearch'));
    if(x.size()>0){
        var search_params = jQuery.parseJSON(x.val());
        return (search_params.zeitraum ? search_params.zeitraum : false);
    }
    return false;
}

function update_price_box($object,house,from,to,fixflex,dur){
    var pdata = {
        "house":house,
        "from":from,
        "to":to,
        "fixflex":fixflex,
        "dur":dur
    }
    $.ajax({
        url:'/xhr/price_house',
        data:pdata,
        dataType:'json',
        type:'post',
        beforeSend:function(){$object.addClass('loading');},
        success:function( response ){
            $object.removeClass('loading');
            if(response){
                $object.addClass(response.house_status_class).addClass(response.price_status);
                $object.find('div.priceBox').html(
                    '<ul><li class="subInfo1 subInfo">'+ response.pers+' Pers. / '+response.dur+' N&auml;chte</li><li class="price">'+response.price+'</li><li class="subInfo2 subInfo">'+response.from+' - '+response.to+'</li></ul>'
                );
                $object.find('h3').prepend(
                   '<span class="status">'+response.house_status_text+'</span>'
                );
                var detaillink = $object.find('li.buttonDetail a');
                var href = detaillink.attr('href')+'/fix/'+house+'_'+response.from+'_'+response.to+'_'+response.pers;
                detaillink.attr('href',href);
            }
        },
        error:function(){$object.removeClass('loading');}
    });
}

(function($) {
    $.fn.emptySelect = function() {
        return this.each(function() {
            if (this.tagName == 'SELECT') this.options.length = 0;
        });
    }

    $.fn.loadSelect = function(optionsDataArray) {
        return this.emptySelect().each(function() {
            if (this.tagName == 'SELECT') {
                var selectElement = this;
                $.each(optionsDataArray, function(index, optionData) {
                    var option = new Option(optionData.label, optionData.value);

                    if ($.browser.msie) {
                        selectElement.add(option);
                    }
                    else {
                        selectElement.add(option, null);
                    }
                });
            }
        });
    }
})(jQuery);

