$(document).ready(function() {
    /// CONTENT WRAPPER BG HEIGHT
    resizeContentWrapperBG();
    /// FAST BOOKING
    fastBookingFunctionalities();
    /// FOCUS DETAIL
    focusDetailFunctionalities();
	/// SCROLL TOP
    scrollTopFunctionalities();
    /// CACHE KILLER
    addParameterToAvoidCache();
    /// gallery
    fancyBoxFunctionalities();
    /// room gallery
    roomGalleryFunctionalities();
    /// expandable interaction
    expandableFunctionalities();
    /// BOOKING
    datePickerInteraction();
    /// FOOTERLOGOS
    footerLogoInteraction();

});
$(window).resize(function() {
    /// CONTENT WRAPPER BG HEIGHT
    resizeContentWrapperBG();
}).load(function() {
        /// CONTENT WRAPPER BG HEIGHT
        resizeContentWrapperBG();
});

/* handle root */
var custom_basePath = "/";
var custom_docRootPath = "docroot/customdir/";
var custom_fullDocRootPath = custom_basePath+custom_docRootPath;
function setCustomBasePath(p){
    if(p.lastIndexOf("/")!=p.length){p=p+"/"}
    custom_basePath = p;
    custom_fullDocRootPath = custom_basePath+custom_docRootPath;
    checkForMobileDevice(custom_fullDocRootPath);
}

/* check for mobile */

var isMobileDevice = false;
function checkForMobileDevice(custom_fullDocRootPath){
    var usAg = window.navigator.userAgent;
    if (screen.width < 500 || usAg.match(/Android/i) || usAg.match(/webOS/i) || usAg.match(/iPad/i) || usAg.match(/iPhone/i) || usAg.match(/iPod/i) || usAg.match(/BlackBerry/i)) {
        isMobileDevice = true;
    }
    var isIos5 = usAg.indexOf("like Mac OS X")!=-1 && usAg.indexOf("OS 5_")!=-1;

    if(isMobileDevice && !isIos5){
        $("head").append('<link rel="stylesheet" type="text/css" media="screen" href="'+custom_fullDocRootPath+'css/mobile.css" />');
    }
}


function expandableFunctionalities(){
    $(".expandable h2").click(function(){
        $(this).parent().find(".expandableEntries").slideToggle();
    });
}


function roomGalleryFunctionalities(){
    $(".roomGallery a").click(function(e){
        e.preventDefault();
        var i = $(this);
        var p = i.parent().parent();
        var d = p.find(".roomGalleryDetail");
        var b = i.attr("href");
        if(i.hasClass("active")){
            p.find(".active").removeClass("active");
            d.slideUp("fast",function(){resizeContentWrapperBG();});
        }else{
            displayRoomGalleryIndex(b,p,i,d);
        }
    });
    $(".roomGalleryDetail").click(function(){
        var p = $(this).parent().parent();
        var as = p.find(".roomGallery a");
        var aa = p.find(".roomGallery a.active");
        //get current image
        var i = as.index(aa);
        i++;
        if(i>=as.length){i=0;}
        var nxt = $(as.get(i));
        var b = $(as.get(i)).attr("href");
        displayRoomGalleryIndex(b,p,nxt,$(this));
    });
}
function displayRoomGalleryIndex(b,p,i,d){
    var h3 = p.parent().parent().find("h3").text();
    $('<img />').attr('src', b).load(function(){
        p.find(".active").removeClass("active");
        i.addClass("active");
//                d.css("height",this.height+"px");
        b = "<img src='"+b+"' alt='"+h3+"'/>";
        d.html(b);
        d.slideDown("fast",function(){
            resizeContentWrapperBG();
        });
    });
}
function resizeContentWrapperBG(){
    var cw = $("#contentWrapperBG");
    var wh = $(document).height();
//    var wh = $(window).height();
    var ch = cw.height();
    var ct = cw.offset().top;
    if(ch+ct<wh){
        var d = (wh-ct)-10;
        cw.css("height", d+"px");
    }
}
function fastBookingFunctionalities(){
    $("#fast_booking").submit(function(e){
//        e.preventDefault();
    });
}
function focusDetailFunctionalities(){
    if($.getUrlVar("focusId")!=undefined){
        var $d = $("#"+$.getUrlVar("focusId"));
        if(eventListBackLinkText.length>2){$d.append("<br/><br/><a href='javascript:history.back()'>"+eventListBackLinkText+"</a>");}
        $d.addClass("focusedEvent");
        var t = $d.offset().top;
        $.scrollTo(t-22, 100);
    }
}
function scrollTopFunctionalities(){
    $(window).scroll(function() {
		if($(this).scrollTop() != 0) {
			$('#toTop').fadeIn();
		} else {
			$('#toTop').fadeOut();
		}
	});

	$('#toTop').click(function() {
		$('body,html').animate({scrollTop:0},800);
	});
}


/* inline booking */

var inlineBookingDatePattern = 'dd.mm.yy';
function datePickerInteraction() {
    $("#fast_booking").fadeIn(0);
    $.datepicker.setDefaults($.datepicker.regional['de']);
    setDefaultStartDate();
    $("#bkg_date").datepicker({
        showOn: 'both',
        buttonImage: custom_fullDocRootPath+"images/calendar.gif",
        minDate: +1,
        dateFormat: inlineBookingDatePattern,
        dayNamesMin: ['S', 'M', 'D', 'M', 'D', 'F', 'S'],
        monthNames: ['Januar','Februar','MŠrz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
        firstDay: 1,
        beforeShow: function(input, inst) { window.setTimeout('repositionOpenDatePicker()',150); }
    });
    $("#fast_booking").submit(function(){fillInRoomNo();fillInEnddate()});
}

function repositionOpenDatePicker(){
    var dp = $("#ui-datepicker-div");
    dp.css("top", "auto");
    dp.css("bottom", "32px");
}

function setDefaultStartDate(){
    var date = new Date();
    var d = date.getDate()+1;
    var m = date.getMonth();
    var y = date.getFullYear();
    $("#bkg_date").val($.datepicker.formatDate(inlineBookingDatePattern,new Date(y, m, d)));
    $("#bkg_date_end").val($.datepicker.formatDate(inlineBookingDatePattern,new Date(y, m, d+1)));

}
function fillInRoomNo(){
    var c = $("#bkg_guest").val();
    c = Math.ceil(c/2);
    $("#bkg_rooms").val(c);

}
function fillInEnddate(){
    var start = $("#bkg_date").val();
    var nights = $('#bkg_night').val()*1;
    var date = $.datepicker.parseDate(inlineBookingDatePattern, start);
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();
    var edate= $.datepicker.formatDate(inlineBookingDatePattern,new Date(y, m, d+nights));
    $('#bkg_date_end').val(edate);
}


function footerLogoInteraction(){
    $("#footer_right a img").mouseenter(function(){
        swapFooterLogoMouseOver($(this));
    }).mouseleave(function(){
        swapFooterLogoMouseOver($(this));
    });
}
function swapFooterLogoMouseOver(t){
    var oi = t.parent().attr("rel");
    var ci = t.attr("src");
    t.attr("src", oi);
    t.parent().attr("rel", ci);
}
function setHeaderImagesHandles(arr){
    var i = arr[Math.floor(Math.random()*arr.length)];
    var h = $("#header_image img");
    if(h.length==0){
        $("<img src='"+i+"' />").appendTo("#header_image");
    }else{
        h.attr("src",i);
    }
}
/* header */


/* helper methods */


function fancyBoxFunctionalities(){
    $(".gallery a, a.fancyBox").fancybox({
        'overlayColor'		: '#ffffff',
        'overlayOpacity'	: 0.70,
        'padding'            : 10,
        'margin'            : 40,
        'changeSpeed'        : 0,
        'changeFade'        : 150,
        'titlePosition' 	: 'over',
        'showCloseButton'   : false
    });
}

function addParameterToAvoidCache(){
/* append url parameter to avoid mgnl cache */
    $(".kclink").each(function(){
        var $l = $(this).attr("href");
        if($l.indexOf("?")==-1){
            $l+="?";
        }else{
            $l+="&";
        }
        $l+="kc"+new Date().getTime();
        $(this).attr("href", $l)
    });
}

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});
/* decryp addresses*/
function dcmadr(nnnn){
    var a = "";
    for(i=0,m=nnnn.length;i < m;i++){
        if(i%3==0){
            a += String.fromCharCode(nnnn.substr(i, 3));
        }
    }
    location.href=(a);
}

