/*
function makeReadOnlyById (fieldId)
{
    var field = dojo.byId(fieldId);
    field.readOnly = true;
    field.style.cursor = 'default';
    dojo.connect(field, 'onfocus', function () { field.blur(); });
}
dojo.addOnLoad(
        function() {
                makeReadOnlyById("date_start");
                makeReadOnlyById("date_end");
        }
);
*/


var Cart = [ ];

/**
 * entry { 'ap': String, 'dateStart': Date, 'dateEnd: Date, ['adults': Integer], ['children': Integer] }
 */
function cartAdd (entry)
{
    // search for includes
    diff = dojo.date.difference(entry["dateStart"], entry["dateEnd"]);
    for (var i=0; i<=diff; i++) {
        betweenId = cartFindDate({ "ap": entry["ap"], "date": dojo.date.add(entry["dateStart"], "day", i) });
        if (betweenId !== false) {
            betweenItem = cartGetItem(betweenId);
            compStart = dojo.date.compare(entry["dateStart"], betweenItem["dateStart"], "date");
            compEnd = dojo.date.compare(entry["dateEnd"], betweenItem["dateEnd"], "date");
            if (compStart === -1 && compEnd === 1) {
                // betweenItem is totally included
                //console.debug("found include. removing "+betweenId+".");
                cartRemove(betweenId);
            } else if (compStart === 1 && compEnd === 1) {
                //console.debug("found include. adding "+betweenId+"'s dateStart. removing "+betweenId+".");
                entry["dateStart"] = betweenItem["dateStart"];
                cartRemove(betweenId);
            } else if (compStart === 1 && compEnd === -1) {
                //console.debug("found include. adding "+betweenId+"'s dateEnd. removing "+betweenId+".");
                entry["dateEnd"] = betweenItem["dateEnd"];
                cartRemove(betweenId);
            }
        }
    }
    
    
    // search for direct neighbors
    // before start
    beforeId = cartFindDate({ "ap": entry["ap"], "date": dojo.date.add(entry["dateStart"], "day", -1) });
    beforeDateId = dojo.date.locale.format(dojo.date.add(entry["dateStart"], "day", -1), { datePattern: "yyyyMMdd", selector: "date" });
    if (
        beforeId !== false
        &&
        dojo.byId(entry["ap"]+"_"+beforeDateId)!= undefined
        && 
        dojo.hasClass(entry["ap"]+"_"+beforeDateId, "arrival") === false
    ) {
        //console.debug("found neighbor at start");
        cartEditItem(beforeId, { "dateEnd": entry["dateEnd"] });
    }
    
    // after end
    afterId = cartFindDate({ "ap": entry["ap"], "date": dojo.date.add(entry["dateEnd"], "day", 1) });
    afterDateId = dojo.date.locale.format(dojo.date.add(entry["dateEnd"], "day", 1), { datePattern: "yyyyMMdd", selector: "date" });
    if (
        afterId !== false
        &&
        dojo.byId(entry["ap"]+"_"+afterDateId)!= undefined
        &&
        dojo.hasClass(entry["ap"]+"_"+afterDateId, "departure") === false
    ) {
        //console.debug("found neighbor at end");
        cartEditItem(afterId, { "dateStart": entry["dateStart"] });
    }
    
    // no neighbors
    //console.debug("hasClass 'arrival' (nodeId): ", entry["ap"]+"_"+beforeDateId);
    //console.debug("hasClass 'arrival' (className): ", dojo.byId(entry["ap"]+"_"+beforeDateId));
    //console.debug("hasClass 'departure': ", dojo.hasClass(entry["ap"]+"_"+beforeDateId, "departure"));
    //console.debug("hasClass 'arrival': ", dojo.hasClass(entry["ap"]+"_"+afterDateId, "arrival"));
    if (
        (
            beforeId === false
            ||
            (beforeId !== false && dojo.byId(entry["ap"]+"_"+beforeDateId)!= undefined && dojo.hasClass(entry["ap"]+"_"+beforeDateId, "arrival") !== false)
        )
        &&
        (
            afterId === false
            ||
            (afterId !== false && dojo.byId(entry["ap"]+"_"+afterDateId)!= undefined && dojo.hasClass(entry["ap"]+"_"+afterDateId, "departure") !== false)
        )
    ) {
        if (entry["dateStart"] != undefined && entry["dateEnd"] != undefined) {
            nights = dojo.date.difference(entry["dateStart"], entry["dateEnd"], "day");
        } else {
            nights = 0;
        }
        
        nextId = Cart.length;
        Cart[nextId] = {
            "ap": entry["ap"],
            "dateStart": entry["dateStart"],
            "dateEnd": entry["dateEnd"],
            "nights": nights,
            "adults":  entry["adults"],
            "children": entry["children"],
            "subtotal": cartCalcSinglePeriod(entry["ap"], nights, entry["dateStart"], entry["dateEnd"])
        }
        //console.debug(Cart[nextId]);
    }
    //console.debug(entry.ap);
    setHeaderimage(entry["ap"]);
    
    buildFrontend();
    
    return nextId;
}
function cartEditItem (Id, Props)
{
    for (var index in Props) {
        Cart[Id][index] = Props[index];
    }
    if (Cart[Id]["dateStart"] != undefined && Cart[Id]["dateEnd"] != undefined) {
        Cart[Id]["nights"] = dojo.date.difference(Cart[Id]["dateStart"], Cart[Id]["dateEnd"], "day");
    } else {
        Cart[Id]["nights"] = 0;
    }
}
var overviewEmpty = "";
function buildFrontend () {
    /*
    // frontend output: subtotal
    var subtotal = { };
    subtotal["compact"] = cartCalcSubtotal({ "ap": [ "compact1", "compact2" ] });
    Apartments["compact1"]["currentRate"] = subtotal["compact"]["priceNight"];
    Apartments["compact2"]["currentRate"] = subtotal["compact"]["priceNight"];
    subtotal["large"] = cartCalcSubtotal({ "ap": [ "large1", "large2" ] });
    Apartments["large1"]["currentRate"] = subtotal["large"]["priceNight"];
    Apartments["large2"]["currentRate"] = subtotal["large"]["priceNight"];
    */
    
    for (var ap in Apartments) {
        calendarUnmarkDate(dojo.byId("label_"+ap));
    }
    
    /*
    var totalNights = 0;
    var totalPrice = 0;
    for (var apType in subtotal) {
        //dojo.byId(apType+"_nights").innerHTML = subtotal[apType]["nights"];
        //dojo.byId(apType+"_priceNight").innerHTML = subtotal[apType]["priceNight"] + " EUR";
        //dojo.byId(apType+"_priceTotal").innerHTML = subtotal[apType]["priceTotal"] + " EUR";
        totalNights += subtotal[apType]["nights"];
        totalPrice += subtotal[apType]["priceTotal"];
    }
    //dojo.byId("totalNights").innerHTML = totalNights + " N.";
    */
    dojo.byId("totalPrice").innerHTML = cartCalcTotal() + " EUR";
    
    
    // frontend output: overview
    output = "";
    for (var cartId in Cart) {
        ap = Apartments[Cart[cartId]["ap"]];
        //console.debug(ap);
        calendarMarkDate(dojo.byId("label_"+Cart[cartId]["ap"]));
        //console.debug("label_"+Cart[cartId]["ap"]);
        output +='											<div id="'+cartId+'_row" style="margin-bottom:0px;">'+"\n" +
		'				        <div style="float:left; width:30px;"><a href="javascript:void(0);" onclick="calendarRemoveBookedPeriod('+cartId+');" title="'+LangOverview["del"]+'"><img src="/images/pages/anfrage/delete.png" alt="[X]" style="margin-top:2px;" /></a></div>' +
        '						<!--  style="color:#942923;" --><div style="float:left; width:130px;">'+dojo.date.locale.format(Cart[cartId]["dateStart"], { selector: "date" })+' &ndash; '+dojo.date.locale.format(Cart[cartId]["dateEnd"], { selector: "date" })+'</div>'+
        '                       <div style="float:left; width:65px;">'+Cart[cartId]["nights"]+' '+LangOverview["nights"]+'</div>'+"\n" +
        '						<strong style="float:left; width:75px;">'+ap["title"]+'</strong>'+"\n" +
        '						<input id="'+cartId+'_apName" type="hidden" name="apartments['+cartId+'][apId]" value="'+Cart[cartId]["ap"]+'" />'+"\n" +
        '						<input id="'+cartId+'_dateStart" type="hidden" name="apartments['+cartId+'][dateStart]" value="'+dojo.date.locale.format(Cart[cartId]["dateStart"], { datePattern: "yyyy-MM-dd", selector: "date" })+'" />'+"\n" +
        '						<input id="'+cartId+'_dateEnd" type="hidden" name="apartments['+cartId+'][dateEnd]" value="'+dojo.date.locale.format(Cart[cartId]["dateEnd"], { datePattern: "yyyy-MM-dd", selector: "date" })+'" />'+"\n" +
        '						<div style="float:left; width:60px;">'+"\n" +
        '							<input id="'+cartId+'_adults"'+"\n" +
        '								type="text"'+"\n" +
        '								name="apartments['+cartId+'][adults]"'+"\n" +
        '                               value="1"'+"\n" +
        '								dojoType="dijit.form.NumberTextBox"'+"\n" +
        '								constraints="{min:1,max:'+ap["maxPersons"]+',places:0}"'+"\n" +
        '								promptMessage= "'+LangOverview["msgInfoAdults"]+'"'+"\n" +
        '								required="true"'+"\n" +
        '								invalidMessage="'+LangOverview["msgInvalidAdults"]+'"'+"\n" +
        '								rangeMessage="'+LangOverview["msgRangeAdults1"]+ap["maxPersons"]+LangOverview["msgRangeAdults2"]+'"'+"\n" +
        '								maxlength="1"'+"\n" +
        '								style="float:none; width:45px; margin-left:10px; margin-top:-1px;" />'+"\n" +
        '						</div>'+"\n" +
        '						<div style="float:left; width:60px; margin-left:10px;">'+"\n" +
        '							<input id="'+cartId+'_children"'+"\n" +
        '								type="text"'+"\n" +
        '								name="apartments['+cartId+'][children]"'+"\n" +
        '                               value="0"'+"\n" +
        '								dojoType="dijit.form.NumberTextBox"'+"\n" +
        '								constraints="{min:0,max:'+ap["maxChildren"]+',places:0}"'+"\n" +
        '								promptMessage= "'+LangOverview["msgInfoChildren"]+'"'+"\n" +
        '								required="false"'+"\n" +
        '								invalidMessage="'+LangOverview["msgInvalidChildren"]+'"'+"\n" +
        '								rangeMessage="'+LangOverview["msgRangeChildren1"]+ap["maxChildren"]+LangOverview["msgRangeChildren2"]+'"'+"\n" +
        '								maxlength="1"'+"\n" +
        '								style="float:none; width:45px; margin-left:10px; margin-top:-1px; padding-right:0px;" />'+"\n" +
        '						</div>'+"\n" +
        //'						<div id="'+cartId+'_ppn" style="float:left; width:60px; margin-left:20px; text-align:right;">'+Apartments[Cart[cartId]["ap"]]["currentRate"]+' EUR</div>'+"\n" +
        '						<div id="'+cartId+'_pges" style="float:left; width:110px; margin-left:20px; text-align:right;"><strong>'+(Cart[cartId]["subtotal"])+' EUR</strong></div>'+"\n" +
        '						<div class="cleaner" style="height:5px;"></div>'+"\n" +
        '					</div>'+"\n";
    }
    if (output == "") {
        output = overviewEmpty;
    }
    if (overviewEmpty == "") {
        overviewEmpty = dojo.byId("overview").innerHTML;
    }
    dojo.byId("overview").innerHTML = output;
    
    // destroy all widgets
    dojo.query("input[dojoType]", "overview").forEach(
        function(widget) {
          // For some reason I can't access widget.widgetid; trim the "widget_" prefix off of the id
          var widgetId=widget.id; //.substring(7);
          if (dijit.byId(widgetId)) {
            dijit.byId(widgetId).destroy();
          }
        }
    );
    
    // recreate all widgets
    dojo.parser.parse(dojo.byId("overview"));
    
    
}
function cartGetItem (Id)
{
    if (Cart[Id] != undefined) {
        return Cart[Id];
    } else {
        return false;
    }
}
function cartShow ()
{
    //console.debug(Cart);
}
function cartRemove (id)
{
    // delete item
    Cart.splice(id, 1);
    
    // frontend output
    buildFrontend();
}
function cartFindDate (search)
{
    for (var i=0; i<Cart.length; i++) {
        if (search["ap"] == Cart[i]["ap"] && calendarDateIsBetween(search["date"], Cart[i]["dateStart"], Cart[i]["dateEnd"]) == true) {
            return i;
        }
    }
    return false;
}
function cartCalcTotal () {
    priceTotal =0;
    for (var i=0; i<Cart.length; i++) {
        priceTotal += Cart[i]["subtotal"];
    }
    return priceTotal;
}
function cartCalcSubtotal (search) {
    priceTotal =0;
    for (var i=0; i<Cart.length; i++) {
        nights = 0;
        if (dojo.indexOf(search["ap"], Cart[i]["ap"]) != -1) {
            //console.debug("sum up all nights of the given apartments: (i="+i+")", Cart[i]["nights"]);
            nights += Cart[i]["nights"];
        }
        //console.debug("apType: ", search["ap"][0]);
        Cart[i]["subtotal"] = cartCalcSinglePeriod(search["ap"][0], nights, Cart[i]["dateStart"], Cart[i]["dateEnd"]);
        priceTotal += Cart[i]["subtotal"];
    }
    //prices = cartCalcSinglePeriod(search["ap"][0], nights, Cart[i]["dateStart"], Cart[i]["dateEnd"]);
    /*
    console.debug("cartCalcSubtotal: aps=", search["ap"].join(" "));
    console.debug("cartCalcSubtotal: nights=", nights);
    console.debug("cartCalcSubtotal: prices=", prices);
    */
    
    return { "nights": nights, "priceNight": 0, "priceTotal": priceTotal };
}
function cartCalcSinglePeriod (ap, nights, startDate, endDate)
{
    var Gesamt = 0;
    
    var Preis = 0;
    var MinTage = 0;
    var ZwSumme = 0;
    
    //console.debug("Prices: ", Apartments[ap]["Prices"]);
    for (var Tage in Apartments[ap]["Prices"]) {
        Tage = dojo.number.parse(Tage);
        if (nights >= Tage && Tage > MinTage) {
            Preis = Apartments[ap]["Prices"][Tage];
            MinTage = Tage;
            //console.debug("Tage: " + Tage + " => " + Preis + " EUR");
        }
    } /* end foreach price categories */
    //console.debug("Preis pro Nacht: " + Preis);
    
    // Special Prices
    SpecialPriceTotal = 0;
    SpecialDays = 0;
    dateWalker = startDate;
    while (dojo.date.compare(dateWalker, endDate, "date") < 0) {
        dateWalkerString = dojo.date.locale.format(dateWalker, { selector: "date", datePattern: "yyyyMMdd" });
        if (SpecialPrices[ap] != undefined && SpecialPrices[ap][dateWalkerString] != undefined) {
            //console.debug(dateWalkerString);
            //console.debug(SpecialPrices[ap][dateWalkerString]);
            SpecialDays++;
            SpecialPriceTotal += SpecialPrices[ap][dateWalkerString];
        }
        dateWalker=dojo.date.add(dateWalker, "day", 1);
    }
    
    // Subtotal
    ZwSumme = (nights-SpecialDays) * Preis;
    //console.debug(ZwSumme);
    //console.debug(SpecialPriceTotal);
    ZwSumme = ZwSumme + SpecialPriceTotal;
    //console.debug("Preis gesamt Ap.: " + ZwSumme);
    
    //Gesamt = Gesamt + ZwSumme;
    
    //console.debug("Preis gesamt: " + Gesamt);
    
    return ZwSumme; //Gesamt;
    
} /* end function cartCalcSinglePeriod */
    
function cartCalcSingle (ap, nights)
{
    var Gesamt = 0;
    
    var Preis = 0;
    var MinTage = 0;
    var ZwSumme = 0;
    
    //console.debug("Prices: ", Apartments[ap]["Prices"]);
    for (var Tage in Apartments[ap]["Prices"]) {
        Tage = dojo.number.parse(Tage);
        if (nights >= Tage && Tage > MinTage) {
            Preis = Apartments[ap]["Prices"][Tage];
            MinTage = Tage;
            //console.debug("Tage: " + Tage + " => " + Preis + " EUR");
        }
    } /* end foreach price categories */
    //console.debug("Preis pro Nacht: " + Preis);
    
    ZwSumme = nights * Preis;
    //console.debug("Preis gesamt Ap.: " + ZwSumme);
    
    Gesamt = Gesamt + ZwSumme;
    
    //console.debug("Preis gesamt: " + Gesamt);
    
    return { "priceNight": Preis, "priceTotal": Gesamt };
    
} /* end function cartCalcSingle */

    function calendarMarkPeriod (ap, startDate, endDate) {
        diff = dojo.date.difference(startDate, endDate);
        tmpDate = startDate;
        for (var i=0; i<=diff; i++) {
            tmpDate = dojo.date.add(startDate, "day", i);
            dateId = dojo.date.locale.format(tmpDate, { datePattern: "yyyyMMdd", selector: "date" });
            if (dojo.byId(ap+"_"+dateId) == undefined) {
                return false;
            }
            calendarMarkDate(dojo.byId(ap+"_"+dateId)); //.childNodes[0]);
        }
        return true;
    }
    function calendarCheckPeriod (ap, startDate, endDate) {
        diff = dojo.date.difference(startDate, endDate);
        if (diff < 2) {
            return false;
        }
        
        // check startDate
        dateId = dojo.date.locale.format(startDate, { datePattern: "yyyyMMdd", selector: "date" });
        // free or departure are allowed
        if (
            dojo.byId(ap+"_"+dateId) == undefined
            ||
            dojo.hasClass(ap+"_"+dateId, "occupied")
            ||
            dojo.hasClass(ap+"_"+dateId, "arrival")
        ) {
            return false;
        }
        
        // check endDate
        dateId = dojo.date.locale.format(endDate, { datePattern: "yyyyMMdd", selector: "date" });
        // free or arrival are allowed
        if (
            dojo.byId(ap+"_"+dateId) == undefined
            ||
            dojo.hasClass(ap+"_"+dateId, "occupied")
            ||
            dojo.hasClass(ap+"_"+dateId, "departure")
        ) {
            return false;
        }
        
        // check all days in between
        tmpDate = startDate;
        for (var i=1; i<diff; i++) {
            tmpDate = dojo.date.add(startDate, "day", i);
            dateId = dojo.date.locale.format(tmpDate, { datePattern: "yyyyMMdd", selector: "date" });
            if (
                dojo.byId(ap+"_"+dateId) == undefined
                ||
                dojo.hasClass(ap+"_"+dateId, "occupied")
                ||
                dojo.hasClass(ap+"_"+dateId, "arrival")
                ||
                dojo.hasClass(ap+"_"+dateId, "departure")
            ) {
                return false;
            }
        }
        
        return true;
    }
    function calendarUnmarkPeriod (ap, startDate, endDate) {
        diff = dojo.date.difference(startDate, endDate);
        for (var i=0; i<=diff; i++) {
            tmpDate = dojo.date.add(startDate, "day", i);
            dateId = dojo.date.locale.format(tmpDate, { datePattern: "yyyyMMdd", selector: "date" });
            if (dojo.byId(ap+"_"+dateId) != undefined) {
                calendarUnmarkDate(dojo.byId(ap+"_"+dateId)); //.childNodes[0]);
            }
        }
    }
    
    function calendarMarkDate (obj) {
        if (obj == undefined) {
            return false;
        }
        dojo.addClass(obj, "selected");
        
        return true;
    }
    function calendarUnmarkDate (obj) {
        if (obj == undefined || obj.className == undefined) {
            return false;
        }
        dojo.removeClass(obj, "selected");
        
        return true;
    }
    function calendarDateIsMarked (obj) {
        if (dojo.hasClass(obj, "selected")) {
            return true;
        } else {
            return false;
        }
    }
    
    function calendarDateIsBetween (date, startDate, endDate) {
        compStart = dojo.date.compare(startDate, date, "date");
        compEnd = dojo.date.compare(endDate, date, "date");
        if (
            compStart == 0
            ||
            compEnd == 0
            ||
            (
                compStart < 0
                &&
                compEnd > 0
            )
        ) {
            return true;
        } else {
            return false;
        }
    }
    
    var periods = { };
    var calendarClicks = 0;
    var calendarTmpStartDate;
    var calendarTmpEndDate;
    var calendarTmpAp;
    /*
    var apartments = {
        "compact1": "Compact 1",
        "compact2": "Compact 2",
        "large1": "Large 1",
        "large2": "Large 2"
    };
    */
function calendarRemoveBookedPeriod (cartId) {
    item = cartGetItem(cartId);
    
    // delete from cart
    cartRemove(cartId);
    cartShow();
    
    // unmark
    calendarUnmarkPeriod(item["ap"], item["dateStart"], item["dateEnd"]);
    
    showMsg("del-success");
}

dojo.addOnLoad(function() {
    hh = dojo.byId("calendarHints");
    hh.innerHTML = LangCalMessages["selectionChooseArrival"];
});

function calendarToggleDayBook (obj)
{
    hh = dojo.byId("calendarHints");
    
    obj = obj.parentNode;
    // split apartment and date
    parts = obj.id.split("_");
    //console.debug("mark: split id", parts);
    ap = parts[0];
    
    // parse date into Date object
    date = dojo.date.locale.parse(parts[1], { datePattern: "yyyyMMdd", selector: "date" });
    
    if (calendarClicks === 0) {
        if (calendarDateIsMarked(obj)) {
            // find period
            cartId = cartFindDate({ "ap": ap, "date": date });
            
            // delete from cart
            calendarRemoveBookedPeriod(cartId);
            
            hh.innerHTML = LangCalMessages["selectionChooseArrival"];
            // reset vars
            calendarTmpAp = null;
            calendarTmpEndDate = null;
            calendarTmpStartDate = null;
            calendarClicks = 0;
            
        } else {
            calendarMarkDate(obj);
            calendarClicks++;
            // save date
            calendarTmpAp = ap;
            calendarTmpStartDate = date;
            hh.innerHTML = LangCalMessages["selectionChooseDeparture"];
        }
    } else if (calendarClicks === 1) {
        comp = dojo.date.compare(calendarTmpStartDate, date, "date");
        if (comp !== 0 && comp == true) {
            calendarTmpEndDate = calendarTmpStartDate;
            calendarTmpStartDate = date;
        } else {
            calendarTmpEndDate = date;
        }
        // check if end date is of the same apartment as start date
        // check if date period is valid
            if (calendarTmpAp !== ap || comp === 0 || calendarCheckPeriod(ap, calendarTmpStartDate, calendarTmpEndDate) == false) {
                //console.error("period is NOT bookable");
                showMsg("error");
                // UNmark all dates in between start and end
                calendarUnmarkPeriod(calendarTmpAp, calendarTmpStartDate, calendarTmpEndDate);
            } else {
                //console.log("period is bookable");
                // mark all dates in between start and end
                calendarMarkPeriod(ap, calendarTmpStartDate, calendarTmpEndDate);
                // save date period
                cartAdd({
                    "ap": ap,
                    "dateStart": calendarTmpStartDate,
                    "dateEnd": calendarTmpEndDate,
                    "adults": null,
                    "children": null
                });
                showMsg("success");
                cartShow();
            }
        
        hh.innerHTML = LangCalMessages["selectionChooseArrival"];
        // reset vars
        calendarTmpAp = null;
        calendarTmpEndDate = null;
        calendarTmpStartDate = null;
        calendarClicks = 0;
        /*
        delete calendarTmpAp;
        delete calendarTmpEndDate;
        delete calendarTmpStartDate;
        delete calendarClicks;
        */
    } else {
        hh.innerHTML = LangCalMessages["selectionChooseArrival"];
        // reset vars
        calendarTmpAp = null;
        calendarTmpEndDate = null;
        calendarTmpStartDate = null;
        calendarClicks = 0;
    } // end if calendarClicks == 0
    
    return true;

} // end function


dojo.addOnLoad(function() {
    var parent = dojo.byId("calendarcontainer");
    var moveIt = new dojo.dnd.Moveable("caltooltip", { clickStopsDrag: false });
    
    moveIt.onMouseUp = function (foo) {};
    moveIt.mover.onMouseUp = function () {};
    
    dojo.connect(parent, "onmouseenter",
    function(e) {
        var tooltip = dojo.byId("caltooltip");
        dojo.style(tooltip, {display: "block", top: (e.pageY+15)+'px', left: (e.pageX+10)+'px'});
        moveIt._mover = new moveIt.mover(moveIt.node, e, moveIt);
    });
    
    dojo.connect(parent, "onmouseleave",
    function(e) {
        dojo.style("caltooltip", {display: "none"});
        if (moveIt._mover) {
        //	console.log('destroying..')
            moveIt._mover.destroy();
            delete moveIt._mover;
        }
        dojo.stopEvent(e);
    });
});
function checkTooltip (node, special)
{
    tt = dojo.byId("caltooltip");
    if (dojo.hasClass(node, "free") == true
        ||
        dojo.hasClass(node, "departure") == true
    ) {
        dojo.style(tt, {display: "block"});
        if (special == true) {
            tt.innerHTML = node.childNodes[1].title;
            dojo.addClass(tt, "special");
        } else {
            tt.innerHTML = node.childNodes[1].title;
            dojo.removeClass(tt, "special");
        }
        return;
    } else {
        tt.innerHTML = "";
        dojo.style(tt, {display: "none"});
    }
}

var calmsgTimeoutId;
function showMsg(action) {
    m = dojo.byId("calmsg");
    if (action == "error") {
        m.innerHTML = "<span style=\"color:red;\">"+LangCalMessages["bookingError"]+"</span>";
        timeout = 5; // in sec
    }
    if (action == "success") {
        m.innerHTML = "<span style=\"color:green;\">"+LangCalMessages["bookingSuccess"]+"</span>";
        timeout = 3; // in sec
    }
    if (action == "del-success") {
        m.innerHTML = "<span style=\"color:green;\">"+LangCalMessages["deleteSuccess"]+"</span>";
        timeout = 3; // in sec
    }
    
    // stop fadeOut timer
    if (calmsgTimeoutId != undefined) {
        clearTimeout(calmsgTimeoutId);
        calmsgTimeoutId = undefined;
    }
    dojo.fadeIn({
            node: m,
            duration: 300,
            beforeBegin: function () { dojo.style(m, "display", "inline"); }
        }).play();
    
    calmsgTimeoutId = window.setTimeout(function (m) {
            dojo.fadeOut({
                    node: m,
                    duration: 300,
                    onEnd: function () { dojo.style(m, "display", "none"); }
                }).play()
        },
        timeout*1000,
        m
    );
}

/*
var calScroller;
dojo.addOnLoad(function() {
    calScroller = new Scroller("calendarScrollContainer", 50, 10, 0);
    calScroller.checkEnd();
});
*/


function loadingImgShow (e)
{
    dojo.addClass(e.domNode, "calendarLoading");
    return e.loadingMessage;
}
function loadingImgHide (e)
{
    dojo.removeClass(e.domNode, "calendarLoading");
}


function setHeaderimage (ap)
{
    switch (ap) {
        case 'compact1':
            ap = 'compact-1';
            break;
        case 'compact2':
            ap = 'compact-2';
            break;
        case 'large1':
            ap = 'large-1';
            break;
        case 'large2':
            ap = 'large-2';
            break;
        
        default:
            return false;
    }
    //console.debug(basepathImages+"pages/apartments/"+ap+"/img_pano_0.jpg");
    dojo.byId("img_head").src = basepathImages+"pages/apartments/"+ap+"/img_pano_0.jpg";
}