/* Parameter:
a    gibt an, welche Aktion die Funktion ausfuehren soll.
o    das Objekt, auf das die Aktion angewandt wird.
c1    der Name der ersten Klasse
c2    der Name der zweiten Klasse

Moegliche Aktionen sind:

swap    tauscht Klasse c1 gegen Klasse c2 aus.
add     fuegt Klasse c1 dem Objekt o hinzu.
remove  loescht Klasse c1.
check   prueft, ob Klasse c1 schon dem Objekt o hinzugefuegt wurde und gibt true oder false zurueck.
*/
function cssjs(a,o,c1,c2)
{
    switch (a){
        case 'swap':
        o.className=!cssjs('check',o,c1)?o.className.replace(c2,c1):o.className.replace(c1,c2);
        break;
    case 'add':
        if(!cssjs('check',o,c1)){o.className+=o.className?' '+c1:c1;}
        break;
    case 'remove':
        var rep=o.className.match(' '+c1)?' '+c1:c1;
        o.className=o.className.replace(rep,'');
        break;
    case 'check':
        return new RegExp('\\b'+c1+'\\b').test(o.className)
        break;
  }
}

/*
function stringToDate
returns a date object, converted from a string
string format:
dd#mm#yyyy or dd#mm#yyyy#HH#MM
where "#" -  delimiter (space, minus, dot or another char)

*/
function stringToDate(string) {
    var match;
    if (match = new RegExp('^(\\d{1,2}).(\\d{1,2}).(\\d{2,4}).?((\\d{1,2}).(\\d{1,2}))?$').exec(string) ) {
      return new Date(match[3], match[2] - 1, match[1], (match[5])?match[5]:null, (match[6])?match[6]:null);
    } else {
      return null;
    };
}

/****************************************************************
/****************************************************************
/   Generic funtions
/
/   not ressourcetype specific!!
/
/---begin>>
/**
 * Ralf Dannhauer
 * Januar 2008
 *
 * Startinitialisierung nach dem der DOM fertig geladen ist
 *
 */
function bkinit() {
    //make bookabke days clickable
    //$(".daybookable").click( function() { clickday(this); } );
}
/**
 * Ralf Dannhauer
 * Januar 2008
 *
 * show errormessage in div
 *
 */
function showerror(divid, msgtext, duration) {
    $("#"+divid+" >p").text(msgtext);
    $("#"+divid+" >p").animate({opacity: 1.0}, 3000,
        function() {$("#"+divid+" >p").empty(); });
}

/**
 * Ralf Dannhauer
 * August 2007
 *
 * Step einblenden
 *
 */
function showstep(nextstep, activestep) {

    //alten step ausblenden
    $("#step"+activestep).toggleClass("stepboxinactive");
    //neuen step einblenden
    $("#step"+nextstep).toggleClass("stepboxinactive");
    //neuen activen step setzen
    $("#globalrundata").attr("activestep",nextstep);


    // Navigationsleiste mitfuehren
    cssjs('add',document.getElementById("stepnavlink"+nextstep),'active');
    cssjs('remove',document.getElementById("stepnavlink"+activestep),'active');
}
/*******************************************************
*
*   STEPWORKFLOW
*
*   1. intro - show intro text & ressource type selection
*
*   2. rescal - show ressource calendar and ressource selection
*
*   3. bookform - show reservation overview and personal data form
*
*   4. bookconfirm - show reservation confirmation
*
********************************************************/
/**
*   show intro & ressource type selection
****/
function showintro() {
    //Welcher Step ist aktiv?
    var activestep = $(" #globalrundata").attr("activestep");

    // changes step display
    showstep('intro', activestep);
}
/**
*   show ressource calendar and ressource selection
****/
function showrescal(ressourcetype) {
    //Welcher Step ist aktiv?
    var activestep = $(" #globalrundata").attr("activestep");

    if (!$("#globalrundata").attr("blockedid")) {
        // predisplay functions
        if (preshowrescal(ressourcetype)) {
            // changes step display
            showstep('rescal', activestep);
        }
    } else {
        showstep('rescal', activestep);
    }

    // after display functions
    //aftershowrescal();


}
/**
*   show bookoverview and personal data form
****/
function showbookform() {

    if (!($("#globalrundata").attr("blockedid") && $("#globalrundata").attr("blockedfrom")==$("#globalrundata").attr("clickedfrom") && $("#globalrundata").attr("blockedto")==$("#globalrundata").attr("clickedto"))) {
        //block time so no other can catch while entering personal data
        blocktime($("#steprescal").attr("ressourceloaded"), $("#globalrundata").attr("clickedfrom"), $("#globalrundata").attr("clickedto"), function(response) {
            if (typeof(response.result) == "number") {
                $("#globalrundata").attr("blockedid", response.result);
                $("#globalrundata").attr("blockedfrom", $("#globalrundata").attr("clickedfrom"));
                $("#globalrundata").attr("blockedto", $("#globalrundata").attr("clickedto"));
                showstep('bookform', $(" #globalrundata").attr("activestep"));
            } else {
                alert(response.result);
            }
        }, $("#globalrundata").attr("blockedid"));
    }

}

/**
*   show reservation confirmation
****/
function showbookconfirm() {
    // predisplay functions
    //preshowbookconfirm();   not needed yet
    showstep('bookconfirm', $(" #globalrundata").attr("activestep"));
    // after display functions
    //aftershowbookconfirm();   not needed yet


}

function preshowrescal(ressourcetype) {
    if (ressourcetype != $("#steprescal").attr("restypeloaded")) {
        $.ajax({
            url : ALIASPATH + "/frontends/steprescalday/" + $("#globalrundata").attr("client") + '/' + ressourcetype,
            success : function (data) {
                $("#stepmaincontainer").html(data);
                showrescal(ressourcetype);
            }
        });
        return false;
    } else {
        return true;
    }
}

function blocktime(ressource, from, to, callback, blockedid) {
     $.post(ALIASPATH + '/reservations/blocktime/'+ressource+'/'+from+'/'+to+'/'+blockedid, {}, callback,'json');
}


/*****************************
/ @name: getreservationinfo(reservationid)
/ @author: Jens Krause
/ @date: Mai 2008
/ @params: reservationid Reservation ID
/ @description:  - get information about a reservation
/                - send reservation id to php-function: reservations/getreservationinfo
/
*****************************/
function getreservationinfo(reservationid)
{
    $.post(ALIASPATH + '/reservations/getreservationinfo/'+reservationid, {}, {},'json');
}

/****************************************************************
/   Generic funtions end
/****************************************************************/

/****************************************************************
/****************************************************************
/   Day funtions
/
/   ressourcetype daily!!
/
/---begin>>*/
function changeressource() {
    if ($("#steprescal").attr("ressourceloaded") != $("#ressources").val()) {
        $.ajax({
            url : ALIASPATH + "/ressourcecalendars/daily/" + $("#ressources").val(),
            success : function (data) {
                $("#ressourcecals").html(data);
            }
        });
        $("#steprescal").attr("ressourceloaded", $("#ressources").val())
    }

}
/**
 * Ralf Dannhauer
 * August 2007
 *
 * Monatskalenderreihen ein- ausblenden
 *
 */
function showmonths(newmonths)
{
    if (newmonths==0) {newmonths++}
    var m1=newmonths -1;
    var m2=newmonths;
    m2++;
    for (var i = 0; i <= 11; i++) {
        if (i==newmonths | (i==newmonths-1)  | i==m2) {
            if (i==newmonths) {
                var month = document.getElementById('monthcal' + i);
                var monthtab = document.getElementById('months' + i);
                cssjs('remove',month,'invisible');
                cssjs('add',monthtab,'selected');

            } else {
                var month = document.getElementById('monthcal' + i);
                var monthtab = document.getElementById('months' + i);
                cssjs('remove',month,'invisible');
                cssjs('remove',monthtab,'selected');
            }
        } else {
            var month = document.getElementById('monthcal' + i);
            var monthtab = document.getElementById('months' + i);
            cssjs('add',month,'invisible');
            cssjs('remove',monthtab,'selected');
        }

    }
}

function clickday(daycellid, dummy){
    var vals = daycellid.split("_");
    var ressourceid = parseInt(vals[0]);
    var cellunixtime = parseInt(vals[1]);
    clickdate = new Date(cellunixtime * 1000);

    if($("#bookfromdate").val() == ""){

        doonedayselection(daycellid, cellunixtime, ressourceid, clickdate);
    } else {
        if($("#booktodate").val() == "" && $("#globalrundata").attr("clickedfrom") < cellunixtime){

            dodayselection(daycellid, cellunixtime, ressourceid, clickdate);
        } else {
            resetselection();
            clickday(daycellid, dummy)
        }
    }
}

function doonedayselection(daycellid, cellunixtime, ressourceid, clickdate){
    if(!$("#" + daycellid).hasClass("closed_monthday")){
        $("#globalrundata").attr("clickedfrom", cellunixtime);
        $("#bookfromdate").val(clickdate.getDate() + "." + (clickdate.getMonth() + 1) + "." + clickdate.getFullYear());
        //$("#ressource").val($('#monthcal_'+ressourceid+' b:first-child').text());
        //$("#ressourceid").val(ressourceid)
        $("#" + daycellid).addClass("selected");
    }

}

function dodayselection(daycellid, cellunixtime, resid, clickdate){
    var from = parseInt($("#globalrundata").attr("clickedfrom")) + 86400;
    for(i = from; cellunixtime >= i; i = i + 86400){
        var datum = new Date(i * 1000)
        if($("#" + resid + "_" + i).hasClass("closed")){
            clickdate = new Date((i - 86401) * 1000);
            $("#booktodate").val(clickdate.getDate() + "." + (clickdate.getMonth() + 1) + "." + clickdate.getFullYear());
            break;
        }
        $("#" + resid + "_" + i).addClass("selected");
        //Date changes to Summertime
        if(datum.getDay() == 0 && datum.getMonth() == 2 && datum.getDate() > 24){
            i = i - 3600;
        }
        //Date changes to Wintertime
        if(datum.getDay() == 0 && datum.getMonth() == 9 && datum.getDate() > 24){
            i = i + 3600;
        }
    }
    $("#booktodate").val(clickdate.getDate() + "." + (clickdate.getMonth() + 1) + "." + clickdate.getFullYear());
    return false;
}


function altclickday(daycellid, dummy){

    var vals = daycellid.split("_");
    var ressourceid = parseInt(vals[0]);
    var cellunixtime = parseInt(vals[1]);
    clickdate = new Date(cellunixtime * 1000);



    //check if there is a previous selection
    if ($(".selected").length == 0 &&
    $(".free_selected").length == 0 &&
    $(".closed_selected").length == 0 &&
    $(".selected_closed").length == 0 &&
    !($("#" + daycellid).hasClass("free_closed"))
    //&& !($("#" + daycellid).hasClass("free_closed"))
    ) {
        // no day selected yet and day is clickable
        doonedayselection(daycellid, cellunixtime, ressourceid, clickdate);
    }
    else {

        //check if clicked day is start or end day of previous selection
        if ($("#globalrundata").attr("clickedfrom") == cellunixtime || $("#globalrundata").attr("clickedto") == cellunixtime) {
            //remove one day selection

            if (Math.round(($("#globalrundata").attr("clickedto") - $("#globalrundata").attr("clickedfrom")) / 86400) == 1) {
                undoonedayselection(daycellid, cellunixtime, ressourceid, clickdate);
            }
            else {
                //change previous selection
                                undodayselection(cellunixtime, ressourceid);
            }
        }
        else {
            //only if user clicked outside selection range
            if (cellunixtime < $("#globalrundata").attr("clickedfrom") || cellunixtime > $("#globalrundata").attr("clickedto")) {
                //check if new selection is possible
                if (checkdayselection(parseInt(ressourceid), cellunixtime)) {
                    showerror("errormsg", 'Auswahl nicht moeglich!', 3000);
                }
                else {
                        //selection is possible so mark all days within range
                                        dodayselection(daycellid, cellunixtime, ressourceid, clickdate);
                }
            }
        }
    }
}



//make oneday selection if firstclick
function altdoonedayselection(daycellid, cellunixtime, ressourceid, clickdate){

//test auf Ferien (n�chster tag sind ferien, brich funktion ab)
var enddaycellid = ressourceid + "_" + (cellunixtime + addday(cellunixtime));
if ($("#" + enddaycellid).hasClass("holiday_closed"))
        {
                return false;

        }

        //Neue Reservierung -> Form einblenden
        //new_reservation(ressourceid);

        $("#globalrundata").attr("clickedfrom", cellunixtime);
        $("#globalrundata").attr("clickedto", (cellunixtime + addday(cellunixtime)));
        $("#bookfromdate").val(clickdate.getDate() + "." + (clickdate.getMonth() + 1) + "." + clickdate.getFullYear());
        var newdate = new Date((cellunixtime + addday(cellunixtime)) * 1000);
        $("#booktodate").val(newdate.getDate() + "." + (newdate.getMonth() + 1) + "." + newdate.getFullYear());
        $("#bookobjekt").val($('#ressources :selected').text());
    $("#ressource").val($('#monthcal_'+ressourceid+' b:first-child').text())
        //mark first day
        if ($("#" + daycellid).hasClass("closed_free")) {
                $("#" + daycellid).addClass("closed_selected");
                $("#" + daycellid).removeClass("closed_free");
        }
        else {
                $("#" + daycellid).addClass("free_selected");
        }
        //mark end day (automatic 1 day after from day)
        var enddaycellid = ressourceid + "_" + (cellunixtime + addday(cellunixtime));
        if ($("#" + enddaycellid).hasClass("free_closed")) {
                $("#" + enddaycellid).addClass("selected_closed");
                $("#" + enddaycellid).removeClass("free_closed");
        }
        else {
                $("#" + enddaycellid).addClass("selected_free");
        }
}

function altundoonedayselection(daycellid, cellunixtime, ressourceid, clickdate){
        //reset css classes
        //start day
        if ($("#" + ressourceid + "_" + $("#globalrundata").attr("clickedfrom")).hasClass("free_selected")) {
                $("#" + ressourceid + "_" + $("#globalrundata").attr("clickedfrom")).removeClass("free_selected");
        }
        else {
                $("#" + ressourceid + "_" + $("#globalrundata").attr("clickedfrom")).addClass("closed_free");
                $("#" + ressourceid + "_" + $("#globalrundata").attr("clickedfrom")).removeClass("closed_selected");
        }
        //end day
        if ($("#" + ressourceid + "_" + $("#globalrundata").attr("clickedto")).hasClass("selected_free")) {
                $("#" + ressourceid + "_" + $("#globalrundata").attr("clickedto")).removeClass("selected_free");
        }
        else {
                $("#" + ressourceid + "_" + $("#globalrundata").attr("clickedto")).addClass("free_closed");
                $("#" + ressourceid + "_" + $("#globalrundata").attr("clickedto")).removeClass("selected_closed");
        }
        //reset globalrun data and bookform
        $("#globalrundata").attr("clickedfrom", "");
        $("#globalrundata").attr("clickedto", "");
        $("#bookfromdate").val("");
        $("#booktodate").val("");
        $("#bookobjekt").val("");
}

//mark all days within selected range ass selected
function altdodayselection(daycellid, cellunixtime, resid, clickdate){

    if (cellunixtime > parseInt($("#globalrundata").attr("clickedto"))) {
        var unixtime1 = parseInt($("#globalrundata").attr("clickedto"));
        var unixtime2 = cellunixtime;
        //go future
        while (unixtime1 <= unixtime2) {
            switch (unixtime1) {
                case cellunixtime:
                    //mark last day different
                    if ($("#" + resid + "_" + unixtime1).hasClass("free_closed")) {
                        $("#" + resid + "_" + unixtime1).addClass("selected_closed");
                        $("#" + resid + "_" + unixtime1).removeClass("free_closed");
                    }
                    else {
                        $("#" + resid + "_" + unixtime1).addClass("selected_free");
                    }
                    break;
                case parseInt($("#globalrundata").attr("clickedto")):
                    $("#" + resid + "_" + unixtime1).addClass("selected");
                    $("#" + resid + "_" + unixtime1).removeClass("selected_free");
                    break;
                default:
                    $("#" + resid + "_" + unixtime1).addClass("selected");
                    break;
            }
            unixtime1 += addday(unixtime1);
        }
        // set global rundata
        $("#globalrundata").attr("clickedto", cellunixtime);
        var newdate = new Date(cellunixtime * 1000);
        $("#booktodate").val(newdate.getDate() + "." + (newdate.getMonth() + 1) + "." + newdate.getFullYear());
    }
    else {
        //go past
        var unixtime1 = cellunixtime;
        var unixtime2 = parseInt($("#globalrundata").attr("clickedfrom"));
        while (unixtime1 <= unixtime2) {
            switch (unixtime1) {
                                case cellunixtime:
                                        //mark first day different
                                        if ($("#" + resid + "_" + unixtime1).hasClass("closed_free")) {
                                                $("#" + resid + "_" + unixtime1).addClass("closed_selected");
                                                $("#" + resid + "_" + unixtime1).removeClass("closed_free");
                                        }
                                        else {
                                                $("#" + resid + "_" + unixtime1).addClass("free_selected");
                                        }
                                        break;
                                case parseInt($("#globalrundata").attr("clickedfrom")):
                                        $("#" + resid + "_" + unixtime1).addClass("selected");
                                        $("#" + resid + "_" + unixtime1).removeClass("free_selected");
                                        break;
                                default:
                                        $("#" + resid + "_" + unixtime1).addClass("selected");
                                        break;
                        }
            unixtime1 += addday(unixtime1);
        }
        // set global rundata
        $("#globalrundata").attr("clickedfrom", cellunixtime);
        $("#bookfromdate").val(clickdate.getDate() + "." + (clickdate.getMonth() + 1) + "." + clickdate.getFullYear());
    }
}
//unselect all selected days but leave one day selection
function altundodayselection(cellunixtime, resid){
        if (cellunixtime == parseInt($("#globalrundata").attr("clickedto"))) {
                var newclickedto = parseInt(parseInt($("#globalrundata").attr("clickedfrom")) + addday(parseInt($("#globalrundata").attr("clickedfrom"))));
                var unixtime1 = newclickedto;
                var unixtime2 = cellunixtime;
                //removed right side of selection
                while (unixtime1 <= unixtime2) {
                        switch (unixtime1) {
                                case cellunixtime:
                                        //mark last day different
                                        if ($("#" + resid + "_" + unixtime1).hasClass("selected_closed")) {
                                                $("#" + resid + "_" + unixtime1).addClass("free_closed");
                                                $("#" + resid + "_" + unixtime1).removeClass("selected_closed");
                                        }
                                        else {
                                                $("#" + resid + "_" + unixtime1).removeClass("selected_free");
                                        }
                                        break;
                                case newclickedto:
                                        $("#" + resid + "_" + unixtime1).addClass("selected_free");
                                        $("#" + resid + "_" + unixtime1).removeClass("selected");
                                        break;
                                default:
                                        $("#" + resid + "_" + unixtime1).removeClass("selected");
                                        break;
                        }
                        unixtime1 += addday(unixtime1);
                }
                // set global rundata
                $("#globalrundata").attr("clickedto", newclickedto);
                var newdate = new Date(newclickedto * 1000);
                $("#booktodate").val(newdate.getDate() + "." + (newdate.getMonth() + 1) + "." + newdate.getFullYear());
        }
        else {
                //remove left side of selection
                var newclickedfrom = parseInt($("#globalrundata").attr("clickedto") - subday(parseInt($("#globalrundata").attr("clickedto"))));
                var unixtime1 = cellunixtime;
                var unixtime2 = newclickedfrom;
                while (unixtime1 <= unixtime2) {
                        switch (unixtime1) {
                                case cellunixtime:
                                        //mark first day different
                                        if ($("#" + resid + "_" + unixtime1).hasClass("closed_selected")) {
                                                $("#" + resid + "_" + unixtime1).addClass("closed_free");
                                                $("#" + resid + "_" + unixtime1).removeClass("closed_selected");
                                        }
                                        else {
                                                $("#" + resid + "_" + unixtime1).removeClass("free_selected");
                                        }
                                        break;
                                case newclickedfrom:
                                        $("#" + resid + "_" + unixtime1).addClass("free_selected");
                                        $("#" + resid + "_" + unixtime1).removeClass("selected");
                                        break;
                                default:
                                        $("#" + resid + "_" + unixtime1).removeClass("selected");
                                        break;
                        }
                        unixtime1 += addday(unixtime1);
                }
                // set global rundata
                $("#globalrundata").attr("clickedfrom", newclickedfrom);
                var newdate = new Date(newclickedfrom * 1000);
                $("#bookfromdate").val(newdate.getDate() + "." + (newdate.getMonth() + 1) + "." + newdate.getFullYear());
        }
}

function resetselection(){
        $(".selected").each(function(i){
                $("#"+this.id).removeClass("selected");
        });
        $(".free_selected").each(function(i){
                $("#"+this.id).removeClass("free_selected");
        });
        $(".selected_free").each(function(i){
                $("#"+this.id).removeClass("selected_free");
        });
        $(".selected_closed").each(function(i){
                $("#"+this.id).addClass("free_closed");
                $("#"+this.id).removeClass("selected_closed");
        });
        $(".closed_selected").each(function(i){
                $("#"+this.id).addClass("closed_free");
                $("#"+this.id).removeClass("closed_selected");
        });

    $("#bookfromdate").val("");
    $("#booktodate").val("");
    $("#ressource").val("")

}

//selection check
//checks that there's no unavailable day between to dates
//returns true if closed day is found
function checkdayselection(resid, unixtime){
        if (unixtime > parseInt($("#globalrundata").attr("clickedto"))) { //clicked day is in the future
                unixtime1 = parseInt($("#globalrundata").attr("clickedto"));
                unixtime2 = unixtime;
                while (unixtime1 <= unixtime2) {
                        if ($("#" + resid + "_" + unixtime1).hasClass("free_closed") &&
                        unixtime1 != unixtime2 ||
                        $("#" + resid + "_" + unixtime1).hasClass("closed_free") ||
                        $("#" + resid + "_" + unixtime1).hasClass("closed") ||
                        $("#" + resid + "_" + unixtime1).hasClass("holiday_closed"))
                        {
                                return true;
                        }
                        unixtime1 += addday(unixtime1);
                }
        }
        else {
                // clicked day is in the past
                unixtime1 = unixtime;
                unixtime2 = parseInt($("#globalrundata").attr("clickedfrom"));
                while (unixtime1 <= unixtime2) {
                        if (($("#" + resid + "_" + unixtime1).hasClass("closed") ||
                        $("#" + resid + "_" + unixtime1).hasClass("holiday_closed") ||
                        $("#" + resid + "_" + unixtime1).hasClass("free_closed")) &&
                        unixtime1 != unixtime2) {
                                return true;
                        }
                        unixtime1 += addday(unixtime1);
                }
        }
}

//returns diff between two days in minutes (consider summer-winter time change)
function addday(ts) {
    tdate = new Date(ts*1000);
    d=tdate.getDate();
    m=tdate.getMonth();
    y=tdate.getFullYear();
    onedaymore = new Date(y, m, (d+1));
    return (onedaymore.getTime()/1000-ts);
}

//returns diff between two days in minutes (consider summer-winter time change)
function subday(ts) {
    tdate = new Date(ts*1000);
    d=tdate.getDate();
    m=tdate.getMonth();
    y=tdate.getFullYear();
    onedayless = new Date(y, m, (d-1));
    return (ts-onedayless.getTime()/1000);
}
//selection check
//checks if there's no unavailable day between to dates
function markdayselection(resid, unixtime1, unixtime2) {
    while (unixtime1 <= unixtime2) {
        $("#" + resid + "_" + unixtime1).addClass("selected");
        unixtime1+=addday(unixtime1);
    }
}

/****************************************************************
/   daily funtions end
/****************************************************************/

/****************************************************************
/ functions for calendar navigation start
/ @author: Jens Krause
/ @date: Mai 2008
/ @params: res_id Ressource ID
/ @params: month_id ID of the actual month (month_id=0)
/ @description: hide or show the month calendars
/
****************************************************************/

/*****************************
/ @name: next_month(res_id, month_id)
/ @author: Jens Krause
/ @date: Mai 2008
/ @description: show next month and hide previous
/
*****************************/
function next_month(res_id, month_id)
{

    // IDs der Monatskalender
    // test_month prueft Existenz eines Monats ausserhalb aktueller Darstellung (Navigation einblenden?)
    var go_out=month_id;
    var come_in=3+month_id;
    var test_month=month_id+4;
    var next_go_out=1+go_out;

    //html id's zusammenbauen
    var raus='#'+res_id+'_monthcal'+go_out;
    var rein='#'+res_id+'_monthcal'+come_in;
    var rein_test='#'+res_id+'_monthcal'+test_month;

    // Test auf Existenz des n�chsten Monats
    test_it_prev=$(rein_test).html();
    if(test_it_prev==null)
    {
    // Test auf vorherigen bzw. naechsten Monat gescheitert
    // Navigationspfeile weg
        $("a#"+res_id+"_nextmonth").html('');
    }


        // alles ok, alter Monat raus, neuer rein
    $(raus).hide();
    $(rein).show();
        // Navigation aktualisieren
    $("a#"+res_id+"_nextmonth").attr( "href", "javascript:next_month("+res_id+", "+next_go_out+")");
    $("a#"+res_id+"_prevmonth").attr( "href", "javascript:prev_month("+res_id+", "+come_in+")");
    $("a#"+res_id+"_prevmonth").html('<');


}

/*****************************
/ @name: prev_month(res_id, month_id)
/ @author: Jens Krause
/ @date: Mai 2008
/ @description: show previous month and hide next
/
*****************************/

function prev_month(res_id, month_id)
{
    // IDs der Monatskalender
    // test_month prueft Existenz eines Monats ausserhalb aktueller Darstellung (Navigation einblenden?)
    var go_out=month_id;
    var come_in=month_id-3;
    var test_month=month_id-4;
    var next_go_out=go_out-1;

    //html id's zusammenbauen
    var raus='#'+res_id+'_monthcal'+go_out;
    var rein='#'+res_id+'_monthcal'+come_in;
    var rein_test='#'+res_id+'_monthcal'+test_month;

    // Test auf Existenz des vorherigen Monats
    test_it_prev=$(rein_test).html();
    if(test_it_prev==null)
    {
    //Test auf vorherigen bzw. naechsten Monat gescheitert
        $("a#"+res_id+"_prevmonth").html('');
    }

    //Test auf vorherigen bzw. naechsten Monat erfolgreich
    // alt raus, neu rein
    $(raus).hide();
    $(rein).show();

    //Umschreiben der Navigations
    $("a#"+res_id+"_nextmonth").attr( "href", "javascript:next_month("+res_id+", "+come_in+")");
    $("a#"+res_id+"_prevmonth").attr( "href", "javascript:prev_month("+res_id+", "+next_go_out+")");
    $("a#"+res_id+"_nextmonth").html('>');
    }

/****************************************************************
/ functions for calendar navigation end
*****************************************************************/
/*****************************
/ @name: getUsers()
/ @author: Ralf Dannehauer
/ @date: Maerz 2008
/ @params:
/ @description:  - testfunction to get user infos
/
*****************************/

function getUsers (){

    new Ajax.Request(ALIASPATH + '/users/test/json', {
    method:'get',
    onSuccess: function(transport){
        var response = transport.responseText || "no response text";
        try
        {
            var myJson = eval( "(" + response + ")");
            alert(myJson.Client.id);
        }
        catch(err)
        {
            $("tester").innerHTML = err.message + "\n" + response;
        }
    },
    onFailure: function(){ alert('Something went wrong...') }
    });
}

/*****************************
/ @name: show_reservation_detail
/ @author: Jens Krause
/ @date: Mai 2008
/ @description: - show reservation form
/                               - get reservation information
/                               - start function to fill form inputs
*****************************/
function show_reservation_detail(reservation_id, calendar_id)
{
    // reservation form
    var rein='#reservierungs_form';
    // actual calendar
    var rein_3='#monthcal_'+calendar_id;

    var raus='.manage_reservation_form';
    // all calendar of one ressource
    var raus_3=".monthcal_backend"

/******************************************************
/ hide everything, except calendar of actual ressource
/ and reservation form
******************************************************/
    $(raus).hide();
    $(raus_3).hide();
    $(rein).show();
    $(rein_3).show();

/******************************************************
/ update the reservationform button for edit, save or cancel reservation
******************************************************/

    $("#resservation_edit_button").attr({onclick:'edit_reservation_detail('+reservation_id+', '+calendar_id+')'});
    $("#resservation_save_button").attr({onclick:'save_reservation_detail('+reservation_id+', '+calendar_id+')'});
    $("#resservation_cancel_button").attr({onclick:'cancel_reservation('+reservation_id+')'});
    $("#reservierungsdaten_id").html(reservation_id);

/******************************************************
/ send post to reservations/getreservationinfo (php)
/ result is catched in reservation_fill_booked_static (js)
******************************************************/

    $.post(ALIASPATH + '/reservations/getreservationinfo/'+reservation_id, {}, reservation_fill_booked_static,'json');
}

/*****************************
/ @name: edit_reservation_detail
/ @author: Jens Krause
/ @date: Mai 2008
/ @params: reservation_id Reservation ID
/ @params: calendar_id Calendar ID
/ @description: - make reservation form inputs editable
*****************************/
function edit_reservation_detail(reservation_id, calendar_id)
{
    // show reservation form
    var rein='#reservierungs_form';
    //show save button
    var rein_2='#button_save';
    //show reservation calendar
    var rein_3='#monthcal_'+calendar_id;

    // hide other reservation calendars
    var raus='.manage_reservation_form';
    // hide Edit button
    var raus_2='#button_edit';
    var raus_3=".monthcal_backend"

    $(raus).hide();
    $(raus_2).hide();
    $(raus_3).hide();

    $(rein).show();
    $(rein_2).show();
    $(rein_3).show();

    // fill data into editable inputs
    reservation_fill_booked_edit();

}

/*****************************
/ @name: save_reservation_detail
/ @author: Jens Krause
/ @date: Mai 2008
/ @params: reservation_id Reservation ID
/ @params: calendar_id Calendar ID
/ @description:   - send reservation information to save to php (reservations/savereservationinfo)
/                 - update tooltips
/                 - validate reservation data
/                 - set fields editable/ readonly
*****************************/
function save_reservation_detail(reservation_id, calendar_id)
{

    // hide autocomplete box
    $('#suggestions').hide();

    //VALIDATION IF USERNAME IS SET
    // else alert and abort
    var username=$("#reservation_email").attr("value");
    if(username==undefined)
    {
        alert('Bitte geben Sie einen Nutzernamen ein!');
        $("#reservation_email")[0].focus();
        return false;
    }

    //form data prepared
    var data = $("#reservation_save_form").formSerialize();
    //send post to reservations/savereservationinfo (php)
    //callbackfunction renew_span (js)
    $.post(ALIASPATH + '/reservations/savereservationinfo/'+reservation_id, data, renew_span,'json');

    // Form ausblenden
    var raus='#reservierungs_form';

    //evt. Aenderungen im Datum --> muss als reserviert markiert werden
    id=$("#reservation_ressource_id").attr('value');
    start=parseInt($("#globalrundata").attr("clickedfrom"));
    end=parseInt($("#globalrundata").attr("clickedto"));

    var dummy=start;
    while (dummy<(end+1))
        {
        $("#"+id+'_'+dummy).attr({className:"closed monthday"});
        $("#"+id+'_'+dummy+" a").attr({onclick:"javascript:show_reservation_detail('"+reservation_id+"','"+id+"')", href:"#reservierung_"+reservation_id});
        dummy=dummy+86400;
        }
        //Emailfeld f�llten hidden input username--> nach speichern nicht mehr zu editieren
    $("#reservation_email").attr({readonly:"readonly", className:"reservation_input"});
}

/*****************************
/ @name: cancel_reservation
/ @author: Jens Krause
/ @date: Mai 2008
/ @params: reservation_id Reservation ID
/ @description:   - cancel reservation information and send to php (reservations/cancelreservation)
*****************************/
function cancel_reservation(reservation_id)
{
    alert('Wollen Sie diese Reservierung(ID:'+reservation_id+') wirklich entfernen?');
    $.post(ALIASPATH + '/reservations/cancelreservation/'+reservation_id,{}, clean_canceled,'json');
}

/*****************************
/ @name: clean_canceled
/ @author: Jens Krause
/ @date: Mai 2008
/ @params: reservation_id Reservation ID
/ @description:   - callback function
/ @description:   - remove the canceled reservation from Calendar
*****************************/
function clean_canceled(data)
{
    //@params: id= Ressource ID
    //@params: start/end Start/Enddate of reservation
    id=data.result.reservation.ressource_id;
    start=parseInt(data.result.reservation.begin);
    end=parseInt(data.result.reservation.end);

        var dummy=start;
        while (dummy<(end+1))
        {
                //alert('Tag ausblenden:'+id+'_'+dummy);
                $("#"+id+'_'+dummy).attr({className:"monthday"});
                $("#"+id+'_'+dummy+" a").attr({onclick:"", href:"javascript:clickday('"+id+"_"+dummy+"','"+id+"')"});
                dummy=dummy+86400;
        }

}

/*****************************
/ @name: renew_span()
/ @author: Jens Krause
/ @date: April 2008
/ @params: data: - data from reservation form
/ @description:  - after saving data from reservation form renew display and tooltipps
/
*****************************/
function renew_span(data)
{
        //reservation_id testen!!!!!

        reservation_id=data.result.reservation.id;
        ressource_id=data.result.reservation.ressource_id;

        //tooltip aktualisieren
        var string=$("#reservation_anrede").attr('value')+' '+$("#reservation_name").attr('value')+'<br />';
        string=string+$("#bookfromdate").attr('value')+'-'+$("#booktodate").attr('value')+'<br />';
        string=string+$("#reservation_perscount").attr('value')+' Personen<br />'+$("#reservation_phone").attr('value');

        //neues span fue
        // r tooltipp
        $("#globalrundata").after('<span style="display:none;" id="reservierung_'+reservation_id+'" >'+string+'</span>');
        $("#reservierung_"+reservation_id).html(string);

        tooltipp_string='<script>';
        tooltipp_string +=  "$(\"td.closed\").tooltip({";
        tooltipp_string +=' bodyHandler: function() {';

        tooltipp_string +='if(string=$($(this).children("a").attr("href")).html())';
        tooltipp_string +='return string; ';
        tooltipp_string +='else return "Was geht?"; ';
        tooltipp_string +='      },';
        tooltipp_string +=' track: true,';
        tooltipp_string +=' delay: 0, ';
        tooltipp_string +=' showURL: false,';
        tooltipp_string +=' showBody: " - ",';
        tooltipp_string +=' extraclassName: "pretty",';
        tooltipp_string +=' fixPNG: true, ';
        tooltipp_string +=' opacity: 0.95, ';
        tooltipp_string +=' left: -120  });';
        tooltipp_string +=' </script>';

        start=parseInt(data.result.reservation.begin);
        end=parseInt(data.result.reservation.end);

        var dummy=start;

        while (dummy<(end+1))
        {
                //alert('Tag ausblenden:'+id+'_'+dummy);
                $("#"+id+'_'+dummy).attr({className:"closed monthday"});
                $("#"+id+'_'+dummy+" a").attr({onclick:"javascript:show_reservation_detail('"+reservation_id+"','"+ressource_id+"'); return false;", href:"#reservierung_"+reservation_id});

                dummy=dummy+86400;
        }

        //Speichern /Edit-Buttons aktualisieren
        $("#resservation_edit_button").attr({onclick:'edit_reservation_detail('+reservation_id+', '+ressource_id+')'});
        $("#resservation_save_button").attr({onclick:'save_reservation_detail('+reservation_id+', '+ressource_id+')'});

        var raus='#button_save';
        var rein='#button_edit';
        $(raus).hide();
        $(rein).show();

        $("#tooltip_div").html(tooltipp_string);
        $("#"+id+'_'+start).attr({className:"free_closed monthday"});
        $("#"+id+'_'+end).attr({className:"closed_free monthday"});

}

/*****************************
/ @name: reservation_fill_booked_static
/ @author: Jens Krause
/ @date: April 2008
/ @params: data: - reservationdata
/ @description:  - fill reservation data into reservation form
/
*****************************/
function reservation_fill_booked_static(data) {

        $("#reservation_user_id").attr({value:data.result.user.id, readonly:"readonly", className:"reservation_input"});
        $("#reservation_username").attr({value:data.result.reservation.username, readonly:"readonly", className:"reservation_input"});

        $("#reservation_perscount").attr({value:data.result.reservation.perscount, readonly:"readonly", className:"reservation_input"});
        $("#reservation_id").attr({value:data.result.reservation.id, className:"reservation_input"});
        $("#reservation_ressource_id").attr({value:data.result.reservation.ressource_id, className:"reservation_input"});
        $("#reservation_client_id").attr({value:data.result.reservation.client_id, className:"reservation_input"});
        $("#reservation_status").attr({value:data.result.reservation.status, className:"reservation_input"});

        $("#reservation_name").attr({value:data.result.user.lastname, readonly:"readonly", className:"reservation_input"});
        $("#reservation_firstname").attr({value:data.result.user.firstname, readonly:"readonly", className:"reservation_input"});

        $("#reservation_anrede").attr({value:data.result.user.anrede, readonly:"readonly", className:"reservation_input"});
        $("#reservation_strasse").attr({value:data.result.user.strasse, readonly:"readonly", className:"reservation_input"});
        $("#reservation_hnr").attr({value:data.result.user.hnr, readonly:"readonly", className:"reservation_input"});
        $("#reservation_ort").attr({value:data.result.user.ort, readonly:"readonly", className:"reservation_input"});
        $("#reservation_plz").attr({value:data.result.user.plz, readonly:"readonly", className:"reservation_input"});
        $("#reservation_land").attr({value:data.result.user.country, readonly:"readonly", className:"reservation_input"});
        $("#reservation_phone").attr({value:data.result.user.phone, readonly:"readonly", className:"reservation_input"});
        $("#reservation_email").attr({value:data.result.user.email, readonly:"readonly", className:"reservation_input"});

        $("#globalrundata").attr("resservation_startdate", data.result.reservation.begin);
        $("#globalrundata").attr("resservation_enddate", data.result.reservation.end);

        tdate1 = new Date(data.result.reservation.begin * 1000);
        d_von=tdate1.getDate();
        m_von=tdate1.getMonth();
        m_von=m_von+1;

        y_von=tdate1.getFullYear();

        tdate2 = new Date(data.result.reservation.end * 1000);
        d_bis=tdate2.getDate();
        m_bis=tdate2.getMonth();
        m_bis=m_bis+1;
        y_bis=tdate2.getFullYear();

        $("#bookfromdate").attr({value:d_von+"."+m_von+"."+y_von, readonly:"readonly", className:"reservation_input"});
        $("#booktodate").attr({value:d_bis+"."+m_bis+"."+y_bis, readonly:"readonly", className:"reservation_input"});

}

/*****************************
/ @name: reservation_fill_booked_edit
/ @author: Jens Krause
/ @date: April 2008
/ @params: data: - reservationdata
/ @description:  - make reservation form editable
/
*****************************/
function reservation_fill_booked_edit(data) {
        $("#reservation_username").attr({readonly:"readonly", className:"reservation_input"});
        $("#reservation_perscount").attr({readonly:"", className:"reservation_input_edit"});
        $("#reservation_name").attr({readonly:"", className:"reservation_input_edit"});
        $("#reservation_firstname").attr({readonly:"", className:"reservation_input_edit"});
        $("#reservation_anrede").attr({readonly:"", className:"reservation_input_edit"});
        $("#reservation_strasse").attr({readonly:"", className:"reservation_input_edit"});
        $("#reservation_hnr").attr({readonly:"", className:"reservation_input_edit"});
        $("#reservation_ort").attr({readonly:"", className:"reservation_input_edit"});
        $("#reservation_plz").attr({readonly:"", className:"reservation_input_edit"});
        $("#reservation_land").attr({readonly:"", className:"reservation_input_edit"});
        $("#reservation_phone").attr({readonly:"", className:"reservation_input_edit"});
        $("#reservation_email").attr({readonly:"readonly", className:"reservation_input"});
        $("#reservation_id").attr({readonly:"", className:"reservation_input_edit"});

        $("#bookfromdate").attr({readonly:"readonly", className:"reservation_input"});
        $("#booktodate").attr({readonly:"readonly", className:"reservation_input"});

}

/*****************************
/ @name: close_div()
/ @author: Jens Krause
/ @date: April 2008
/ @params: raus: - id/class of element to hide
/ @description:  - hide element raus
/
*****************************/
function close_div(raus)
{
        var rein=".monthcal_backend";
        $(rein).show();
        $(raus).hide();
}

/*****************************
/ @name: strftime()
/ @author: Jens Krause
/ @date: Mai 2008
/ @params: format: - formatstring
/ @params: timestamp: timestamp of date
/ @description:  - formates a timestamp into a date
/
*****************************/
function strftime(format, timestamp) {
        var t = new Date;
        if (typeof timestamp != 'undefined') t.setTime(timestamp * 1000);
        return t.format(format);
}

/*****************************
/ @name: lookup()
/ @author: Jens Krause
/ @date: Mai 2008
/ @params: inputString: - typed in string
/                                               - look up which User are in db which begin with inputString
/ @description:  - autocomplete Nachname
/
*****************************/
function lookup(inputString) {
    if(inputString.length == 0) {
        // Hide the suggestion box.
        $('#suggestions').hide();
    } else {

        //alert(inputString);
        $.post(ALIASPATH + "/reservations/lookup_usernames/"+inputString, {}, function(data){
           //alert(data);
            if(data['result'].length >0) {      // Ergebnis ->Box einblenden
                $('#suggestions').show();
                $('#suggestions').html(data['result']);
            }
            else $('#suggestions').hide(); //leeres Erbenis -> Box ausblenden

        }, 'json');
    }
} // lookup

/*****************************
/ @name: fill_inputs()
/ @author: Jens Krause
/ @date: Mai 2008
/ @params: id: - User ID
/ @params: username: Username
/ @params: anrede: Anrede
/ @params: lastname: Lastname
/ @params: email: Users Email
/ @params: phone: Phone
/ @params: strasse: Street
/ @params: hnr: house number
/ @params: ort: Ort
/ @params: plz: Postal Code
/ @params: country: Country
/ @description:  - fill inputs in reservation form
/
*****************************/
function fill_inputs(id, username, anrede,lastname, email, phone, strasse, hnr, ort, plz, country) {
 //box ausblenden
   $('#suggestions').hide();
 //neue Userdaten rein
        $("#reservation_username").attr({value: username});
        $("#user_username").attr({value: username});
        $("#reservation_name").attr({value: lastname, onkeyup:'lookup(this.value);', onblur:'$("#suggestions").show();'});
        $("#reservation_anrede").attr({value: anrede});

        $("#reservation_strasse").attr({value: strasse});
        $("#reservation_hnr").attr({value: hnr});
        $("#reservation_ort").attr({value: ort});
        $("#reservation_plz").attr({value: plz});
        $("#reservation_land").attr({value: country});
        $("#reservation_phone").attr({value: phone});
        $("#reservation_email").attr({value: email});
        $("#reservation_user_id").attr({value: id});

}

/*****************************
/ @name: set_days_free_4_update()
/ @author: Jens Krause
/ @date: Mai 2008
/ @description:  - Make Reservationdate in Calendar editable
/
*****************************/
function set_days_free_4_update()
{
        var rein='#button_save';
        $(rein).show();

        id=$("#reservation_ressource_id").attr('value');

        start=parseInt($("#globalrundata").attr("resservation_startdate"));
        end=parseInt($("#globalrundata").attr("resservation_enddate"));
        $("#globalrundata").attr("clickedfrom", start);
        $("#globalrundata").attr("clickedto", end);

        var dummy=start;
        while (dummy<(end+1))
        {

                $("#"+id+'_'+dummy).attr({className:"edit_date daybookable selected"});
                $("#"+id+'_'+dummy+" a").attr({onclick:"", href:"javascript:clickday('"+id+"_"+dummy+"','"+id+"')"});


                dummy=dummy+86400;
        }
        $("#"+id+'_'+start).attr({className:"daybookable edit_date_start free_selected"});
        $("#"+id+'_'+end).attr({className:"daybookable edit_date_end selected_free"});

}

/*****************************
/ @name: set_days_free_4_update()
/ @author: Jens Krause
/ @date: Mai 2008
/ @description:  - Make Reservationdate in Calendar editable
/
*****************************/
function new_reservation(ressourceid)
{
        //Formularfelder leeren
        $("#reservation_user_id").attr({value:""});
        $("#reservation_username").attr({value:""});

        $("#reservation_perscount").attr({value:""});
        //hidden fields
        $("#reservation_id").attr({value:""});
        $("#reservation_ressource_id").attr({value:ressourceid});
        $("#reservation_status").attr({value:"booked"});

        $("#reservation_firstname").attr({value:""});
        $("#reservation_name").attr({value:""});
        $("#reservation_anrede").attr({value:""});
        $("#reservation_strasse").attr({value:""});
        $("#reservation_hnr").attr({value:""});
        $("#reservation_ort").attr({value:""});
        $("#reservation_plz").attr({value:""});
        $("#reservation_land").attr({value:""});
        $("#reservation_phone").attr({value:""});


        // reservation form
    var rein='#reservierungs_form';
    // actual calendar
    var rein_2='#monthcal_'+ressourceid;

    var raus='.manage_reservation_form';
    // all calendar of one ressource
    var raus_2=".monthcal_backend";

    $(raus).hide();
    $(raus_2).hide();
    $(rein).show();
    $(rein_2).show();

        data='';
        reservation_fill_booked_edit(data);

        $("#reservation_email").attr({readonly:"", className:"reservation_input_edit", value:""});

        //bearbeiten und speichern Buttons mit funktionen versehen
        $("#resservation_save_button").attr({onclick:'save_reservation_detail("", '+ressourceid+')'});

        var rein='#button_save';
        var raus='#button_edit';
        $(raus).hide();
        $(rein).show();
}

/*****************************
/ @name: abort_reservation()
/ @author: Jens Krause
/ @date: Maerz 2008
/ @description:  - Abort new Reservation
/
*****************************/
function abort_reservation()
{
        var raus='#reservierungs_form';
        $(raus).hide();

        //Falls bestehende Reservierung editiert wird
        $(".edit_date").attr({className:"closed monthday"});
        $(".edit_date_start").attr({className:"free_closed monthday"});
        $(".edit_date_end").attr({className:"closed_free monthday"});

        //Neue reservierung zuruecksetzen
        $(".selected").attr({className:"monthday"});
        $(".free_selected").attr({className:"monthday"});
        $(".selected_free").attr({className:"monthday"});
}

/*****************************
/ @name: cancel()
/ @author: Jens Krause
/ @date: Mai 2008
/ @description:  - cancel different action
/
*****************************/
function cancel()
{
        // is filled in html code with actual referer
        var referer=$('#referer').attr("value");
        top.location=referer;
}

/*****************************
/ @name: ajax_cancel()
/ @author: Jens Krause
/ @date: Maerz 2008
/ @description:  - cancel reservation form action
/
*****************************/
function ajax_cancel()
{
        // actual Url
        var self=location.pathname;

        top.location=self;
}

/*****************************
/ @name: users_index()
/ @author: Nikiforov Nikolay
/ @date: Mai 2008
/ @description:  - ajax page reload
/
*****************************/
function users_index(url)
{
  $.post( url.toString() , {}, function(data){
    $('#users_index').html(data);
  },'ajax');
}

/*****************************
/ @name: switch_restype()
/ @author: Jens Krause
/ @date: Mai 2008
/ @param:object changeobject: DOM Object of SELECT input
/ @description:  - show/hide options in ressource SELECT depending on value in Ressourcetype SELECT
/
*****************************/
function switch_restype()
{
        $('#Price_calendar').hide();
        dummy=$('#RessourcetypeId option:selected').val();

        /*** Debug  ***/
        dummy_neu=$('#AllRessourceId .restype_'+dummy).clone();

        $('#RessourceId').html(dummy_neu);
        //$('#AllRessourceId option:selected').removeAttr('selected');
        $("#AllRessourceId .empty_option").clone().prependTo("#RessourceId");
        //$('#RessourceId option:selected').removeAttr('selected');
        //$('#RessourceId').selectedIndex()=0;


        dummy_ps=$('#AllPriceSeasons .ps_'+dummy).clone();
        $('#PriceSeasonId').html(dummy_ps);
        //$('#AllPriceSeasons option:selected').removeAttr('selected');
        $("#AllPriceSeasons .ps_0").clone().prependTo("#PriceSeasonId");
        //$('#PriceSeasonId option:selected').removeAttr('selected');

        /**************/


        //Rabatte ausblenden
        $('#form_price_rabatte table').hide();
        $('#price_rabatte').hide();
        $('#show_PriceRabatt').removeAttr('checked');


        if(dummy=='add')
        {
                $('#RessourceId option').hide();
                $('#RessourceId .empty_option').show();
                $('#RessourceId .empty_option').attr({selected: 'selected'});
                $('#price_form div').hide();
                $('#price_form').show();
                $('#new_restype').show();
                $('#RessourceId').attr({disabled:'DISABLED'});
        }
        else
        {
                $('#price_form div').hide();
                $('#price_form').hide();

                //erst nachdem der Ressourcetyp gewaehlt ist, wird DISABLED von Ressource entfernt
                $('#RessourceId').removeAttr('DISABLED');


                //PreisGruppe fuellen
                /*
                / dazu: hole Attribut aus option namens "pricegroup"
                / falls groesser 0 waehle in der select-box (preisgruppe) die zugeordnete Preisgruppe
                / sonst: kopiere Namen in Feld zu anlegen einer neuen Preisgruppe
                */

                var pricegroup_id=$('#RessourcetypeId option:selected').attr('pricegroup');

                if(pricegroup_id>0)
                {
                 $('#PricePriceGroupId option:selected').removeAttr('selected');
                 $('#pg_'+pricegroup_id).attr({selected:'selected'});
                }
                else
                {
                        //var selected_name=changeobject.options[changeobject.options.selectedIndex].text;
                        // Name der Preisgruppe festlegen
                        $('#PricePriceGroupId option:selected').removeAttr('selected');
                        $('#pg_empty').attr({selected:'selected'});
                }

                if(dummy=='')
                {
                        //$('#PriceSeasonId').attr({disabled:'DISABLED'});
                        $('#RessourceId').attr({disabled:'DISABLED'});
                }

        }
}

/*****************************
/ @name: price_new_ressource()
/ @author: Jens Krause
/ @date: Mai 2008
/ @param:object changeobject: DOM Object of SELECT input
/ @description:  - show/hide "new ressource"form in admin/prices/manage
/
*****************************/
function price_new_ressource(changeobject)
{
        $('#Price_calendar').hide();
        var resstype=$('#RessourcetypeId').attr('value');
        var resstype_pg=$('#RessourcetypeId option:selected').attr('pricegroup');

        //Rabatte ausblenden
        $('#form_price_rabatte table').hide();
        $('#price_rabatte').hide();
        $('#show_PriceRabatt').removeAttr('checked');
        $('span.calendar_dayprice').html('xxx');

        if(changeobject.value=='add')
        {
                //$('#PriceSeasonId').attr({disabled:'DISABLED'});
                $('#price_form div').hide();
                $('#price_form').show();
                $('#new_ressource').show();

        //Variablen vorbelegen
        $('#RessourceRessourcetypeId').attr({value:resstype});
        }
        else
        {// keine neue Ressource anlegen sondern vorhandene gewaehlt
                $('#price_form div').hide();
                $('#price_form').hide();

                //PreisGruppe fuellen
                /*
                / dazu: hole Attribut aus option namens "pricegroup"
                / falls groesser 0 waehle in der select-box (preisgruppe) die zugeordnete Preisgruppe
                / sonst: kopiere Namen in Feld zu anlegen einer neuen Preisgruppe
                */

                if(changeobject.value<1)
                {
                        //falls die leere option bei Ressource gewaehlt, setze Preisgruppe auf Werte von RT
                        pricegroup_id=$('#RessourcetypeId option:selected').attr('pricegroup');
                        $('#PricePriceGroupId option:selected').removeAttr('selected');
                        $('#pg_'+pricegroup_id).attr({selected:'selected'});

                        return false;
                }
                var pricegroup_id=$('#RessourceId option:selected').attr('pricegroup');

                if(pricegroup_id>0)
                {
                //vorhandene Preisgruppe
                 $('#PricePriceGroupId option:selected').removeAttr('selected');
                 $('#pg_'+pricegroup_id).attr({selected:'selected'});
                }
                else
                {
                        var selected_name=changeobject.options[changeobject.options.selectedIndex].text;
                        // Name der Preisgruppe festlegen
                        var old_name=$('#RessourcetypeId option:selected').text();
                        $('#PriceGroupName').attr({value:old_name+':'+selected_name});
                        $('#PricePriceGroupId option:selected').removeAttr('selected');
                        $('#pg_empty').attr({selected:'selected'});
                }
        }
}

function price_new_season(changeobject)
{
        $('#Price_calendar').hide();
        $('#flashMessage').hide();

        if(changeobject.value=='')
                {       $('#flashMessage').hide();
                    $('#flashMessage').html('Bitte Preissaison angeben');
                        $('#flashMessage').fadeIn('slow');
                return false;
                }
        if(changeobject.value=='add')
        {
        $('#price_form div').hide();
        $('#price_form').show();
        $('#new_price_season').show();
        }
        else
        {
                $('#price_form div').hide();
                $('#price_form').hide();
        }
}

function price_save_restype()
{
        var form_id='#new_restype_id';

        //form data prepared
    var data = $(form_id).formSerialize();

    //send post to reservierung/admin/ressourcetypes/form_add_save/ (php)
    //callbackfunction price_save_restype_success (js)
    //alert('try 2 save');
    $.post(ALIASPATH + '/admin/ressourcetypes/form_add_save/', data, price_save_restype_success,'json');


}

function price_save_restype_success(data)
{       //alert('saving sucess');
        $("#RessourcetypeId").append('<option value="'+data.result.id+'" selected="selected">'+data.result.name+'</option>');

        // Inputfelder loeschen
        $('#new_restype_id input').attr({value:''});
        $('#new_restype').hide();
        $('#price_form div').hide();
        $('#price_form').hide();
        $('#RessourceId').removeAttr('DISABLED');
        $('#RessourceId .ressource_add').show();
        $('#RessourceId .empty_option').attr({selected: 'selected'});

        //PreisGruppe fuellen
        //Name der selektierten Option
        var selected_name=data.result.name;
        // Name der Preisgruppe festlegen
        $('#PriceGroupName').attr({value:selected_name});

        $('#price_form div').hide();
        $('#price_form').show();
        $('#new_ressource_form').show();

}

function price_save_ressource()
{
        var form_id='#new_ressource_form';

        //form data prepared
    var data = $(form_id).formSerialize();

    //send post to reservierung/admin/ressourcetypes/form_add_save/ (php)
    //callbackfunction price_save_restype_success (js)
    $.post(ALIASPATH + '/admin/ressources/form_add_save/', data, price_save_ressource_sucess,'json');

}

function price_save_ressource_sucess(data)
{
        //alert('Neues Mietobjekt erfolgreich angelegt.');
        $('#flashMessage').hide();
        $('#flashMessage').html(ressource_added);
        $('#flashMessage').fadeIn('slow');

        //Preissaison anwaehlbar machen
        //$('#PriceSeasonId').removeAttr('DISABLED');
        $('#price_form div').hide();
        $('#price_form').hide();


        // Inputfelder loeschen
        $('#new_ressource_form input').attr({value:''});


        //Neue Ressource in select haengen
        $("#RessourceId").append('<option value="'+data.result.id+'" selected="selected" class="restype_'+$('#RessourcetypeId').val()+'">'+data.result.name+'</option>');

                //PreisGruppe fuellen
                //Name der selektierten Option
                var selected_name=data.result.name;
                // Name der Preisgruppe festlegen

                //var old_name=$('#PriceGroupName').attr('value');
                //debugger;
                var old_name=$('#RessourcetypeId option:selected').text();;
                //var old_name=data.result.name;

                $('#PriceGroupName').attr({value:old_name+':'+selected_name});
                $('#PricePriceGroupId option:selected').removeAttr('selected');
                $('#pg_empty').attr({selected:'selected'});




}

function price_save_season()
{
        var form_id='#new_price_season_form';
        //form data prepared
    var data = $(form_id).formSerialize();
    //callbackfunction price_save_season_success (js)
    $.post(ALIASPATH + '/admin/price_seasons/form_add_save/', data, price_save_season_sucess,'json');
}

function price_save_season_sucess(data)
{
        $('#price_form div').hide();
        $('#price_form').hide();
        //Neue Preissaison in select h�ngen
        $("#PriceSeasonId").append('<option value="'+data.result.id+'" selected="selected" class="season_'+$('#RessourcetypeId').val()+'">'+data.result.name+'</option>');
}

function show_pricegroup(obj)
{
        if($('#show_PriceGroup').attr('checked')==true)
        {
                $('#row_pricegroup').show();
                $('#show_PriceGroup').attr({checked:'checked'});
        }
        else
        {
                $('#row_pricegroup').hide();
                $('#show_PriceGroup').removeAttr('checked');
        }
}

function price_new_group(changeobject)
{
        $('#Price_calendar').hide();

        if(changeobject.value=='add')
        {
        $('#price_form div').hide();
        $('#price_form').show();
        $('#new_price_group').show();
        }
        else
        {
                $('#price_form div').hide();
                $('#price_form').hide();
        }
}

function price_save_group()
{
        var form_id='#new_price_group_form';
        //form data prepared
    var data = $(form_id).formSerialize();
    var rt =$('#RessourcetypeId option:selected').val();
    var res= $('#RessourceId option:selected').val();
    var PGname=rt+':'+res;
    //alert(PGname);
    //debugger;
    //callbackfunction price_save_season_success (js)
    $.post(ALIASPATH + '/admin/price_groups/form_add_save/pg_'+rt+'_'+res, data, price_save_group_sucess,'json');
}

function price_save_group_sucess(data)
{
        var dummy=typeof(data.result);
        $('#price_form div').hide();
        $('#price_form').hide();
        //Neue Preissaison in select haengen
        if(dummy!='undefined')
        {
                //alert(dummy);
                $("#PricePriceGroupId").append('<option value="'+data.result.id+'" id="pg_'+data.result.id+'" selected="selected">'+data.result.name+'</option>');

                price_set_pricegroup(data.result.id)
                return data.result.id;
        }
        else return false;
}

function fixedprice_save_group()
{
        var form_id='#new_price_group_form';
        //form data prepared
    var data = $(form_id).formSerialize();
    var rt =$('#RessourcetypeId option:selected').val();
    var res= $('#RessourceId option:selected').val();
    //alert(PGname);
    //debugger;
    //callbackfunction price_save_season_success (js)
    $.post(ALIASPATH + '/admin/price_groups/form_add_save/pg_'+rt+'_'+res, data, fixedprice_save_group_sucess,'json');
}
function fixedprice_save_group_sucess(data)
{
        var dummy=typeof(data.result);
        //Neue Preissaison in select haengen
        if(dummy!='undefined')
        {

                $('#PricePriceGroupId option:selected').val(data.result.id);
                price_save_standard();
                return data.result.id;
        }
        else return false;
}

function price_set_pricegroup(chooser_cb)
{       activity_indicator_start();

        var chooser=$('#PricePriceGroupId option:selected').val();
        var rt=$('#RessourcetypeId option:selected').val();
        var res=$('#RessourceId option:selected').val();
        var season=$('#PriceSeasonId option:selected').val();

        //wenn chooser_cb gesetzt, ist das callback von price_save_group_sucess
        if(chooser_cb)
        {
                chooser=chooser_cb;
                //alert('new chooser:'+chooser);
        }

        //test ob im price_group select:selected was drinsteht
        // ja: setze Gruppenid fuer betroffenen RT / Ressource
        // nein: add-action ausgefuehrt, dann setzen der gruppe


        //alert('chooser :'+chooser);
        if(rt && season && rt>0)
        {
                if(!chooser || chooser<1)
                {
                        // neue Preisgruppe anlegen
                        // danach wird diese funktion mit parameter neu initiert
                        price_save_group();

                }
                else
                {
                        data=new Array();
                        data['RessourceType']=rt;
                        data['Ressource']=res;
                        data['Pricegroup']=chooser;

                        //$('#price_manage_ok').html('<b>TEST</b>');

                        $.post(ALIASPATH + '/admin/price_groups/set_groups/'+chooser+'/'+rt+'/'+res, data, price_set_pricegroup_sucess,'json');
                        // set price_group action

                        $('#form_price_rabatte table').show();
                        $('#standard_form_price_id').val('');
                        $('#PricePrice').val('');
                }
        }
        else
        {
        if(!(rt && rt > 0)){

                $('#flashMessage').hide();
                $('#flashMessage').html(ressourcetype_error);
                $('#flashMessage').fadeIn("slow");
                activity_indicator_stop();

                }

        if(!season){
                activity_indicator_stop();
                }

        return false;
        }
}

function price_set_pricegroup_sucess(data)
{
        var pricegroup_id=data.result.pg;
        var rt_id=data.result.rt;
        var res_id=data.result.res;

                if(pricegroup_id>0)
                {
                //aktuelle Gruppe in Auswahl "selecten"
                 $('#PricePriceGroupId option:selected').removeAttr('selected');
                 $('#pg_'+pricegroup_id).attr({selected:'selected'});

                 //test ob Ressource gewaehlt wurde (bedenke leeres Element in dropdown! [value:0]
                 if(res_id<1)
                 {      //leeres Element als Ressource --> nimm Ressourcetype
                        $('#RessourcetypeId option:selected').attr({pricegroup:pricegroup_id});
                 }
                 else
                 {      // richtige Ressource
                        $('#RessourceId option:selected').attr({pricegroup:pricegroup_id});
                 }
                }

        if($('#manage_identifier').html()=='rabatte')
        {
                $('#price_form').show();
                activity_indicator_stop();
        }
        else
        {
                show_pricecalendar();
        }
}

function show_pricecalendar()
{
        var rt_name=$('#RessourcetypeId option:selected').text();
        var res_id=$('#RessourceId option:selected').val();
                if(!res_id || res_id=='add' || res_id=='0') res_name='<i>'+all+'</i>';
                else res_name=$('#RessourceId option:selected').text();
        var season_name=$('#PriceSeasonId option:selected').text();

        //Fuellen der Anzeigedaten
        $('#price_calendar_head_ressourcetype').html(rt_name);
        $('#price_calendar_head_ressource').html(res_name);
        $('#price_calendar_head_season').html(season_name);


        $('#price_form div').show();
        $('#new_price_group').hide();
        $('#price_form').show();

        $('#price_calendar').show();
        $('#price_calendar_head').show();

        $('#Price_calendar').show();
        $('#form_price_rabatte').show();
        $('#Price_calendar').show();

        preise_holen();

}

function price_save_standard()
{
        var form_id='#form_price_calendar';
        var Price =$('#PricePrice').val();
        var num_checker= Price*1;

        if(Price.length<1 || isNaN(num_checker))
        {
                $('#PricePrice').addClass('error_border');
                return false;
        }
        else
        {
                $('#PricePrice').removeClass('error_border');
        }


        activity_indicator_start();

        chooser='standard';
        //form data prepared
        pricegroup=$('#PricePriceGroupId option:selected').val();


        if(pricegroup<1)
        {
                fixedprice_save_group();
                return false;
        }

        priceseason=$('#PriceSeasonId option:selected').val();

        $('#standard_form_price_group').attr({value:pricegroup});
        $('#standard_form_price_season').attr({value:priceseason});

    var data = $(form_id).formSerialize();
    //callbackfunction price_save_season_success (js)
    $.post(ALIASPATH + '/admin/prices/form_save/'+chooser, data, price_save_standard_sucess,'json');
}

function price_save_standard_sucess(data)
{
        //debugger;
        $('#flashMessage').hide();
        $('#flashMessage').html('gespeichert');
        $('#flashMessage').fadeIn("slow");
        $('span.calendar_dayprice').html(data.result.price);
        preise_holen();
}

function show_price_rabatt(obj)
{
        if($('#show_PriceRabatt').attr('checked')==true)
        {
                $('#price_rabatte').show();
                $('#show_PriceRabatt').attr({checked:'checked'});
                 rabatte_selectbox();
        }
        else
        {
                $('#price_rabatte').hide();
                $('#show_PriceRabatt').removeAttr('checked');
        }
}

function show_price_rabatt_direkt()
{
                $('#price_rabatte').show();
                $('#price_calendar_head').show();
                $('#price_form').show();
                $('#price_calendar').show();
                $('#price_form .headl').show();
                $('#price_form .boldtopborder').show();
                $('#price_form .boldtopborder div').show();
                $('#new_price_group').hide();

                $('#show_PriceRabatt').attr({checked:'checked'});
                 rabatte_selectbox();
}

function show_add_dayprice(dayselector)
{
                switch(dayselector)
                {
                case '1': day=montag; chooser='mo'; td_chooser="#calendar_MO";
                                        break;
                case '2': day=dienstag; chooser='di'; td_chooser="#calendar_DI";
                                        break;
                case '3': day=mittwoch; chooser='mi'; td_chooser="#calendar_MI";
                                        break;
                case '4': day=donnerstag; chooser='do'; td_chooser="#calendar_DO";
                                        break;
                case '5': day=freitag; chooser='fr'; td_chooser="#calendar_FR";
                                        break;
                case '6': day=samstag; chooser='sa'; td_chooser="#calendar_SA";
                                        break;
                case '7': day=sonntag; chooser='so'; td_chooser="#calendar_SO";
                                        break;

                }
                $('div.dayprices').hide();
                //$('#day_'+chooser).show();
                $('.calendar_dayprice_input').hide();
                $('.calendar_dayprice').show();
                $(td_chooser+' .calendar_dayprice').hide();
                $(td_chooser+' .calendar_dayprice_input').show();
                $(td_chooser+' .calendar_dayprice_input input').focus();

                //$('#price_add_dayprice').show();
                //$('#dayprice_chooser').attr({value:chooser});
                //$('#dayprice_chooser_day').attr({value:chooser});

                //day_preise_holen();
                //setTimeout("dayprice_selectbox()",1000);
}

function price_save_dayprice(selector)
{

        var form_id='';
        switch(selector)
                {
                case 'day': form_id='#form_price_add_dayprice_day';
                                        break;
                case 'hour': form_id='#form_price_add_dayprice'; break;
                }

                var Price =$(form_id+' #PricePrice').val();
                var num_checker= Price*1;


                if(Price.length<1 || isNaN(num_checker))
                {
                        $(form_id+' #PricePrice').addClass('error_border');
                        return false;
                }
                else
                {
                        $(form_id+' #PricePrice').removeClass('error_border');
                }
        activity_indicator_start();

        //form data prepared
        chooser=$('#dayprice_chooser').val();
        pricegroup=$('#PricePriceGroupId option:selected').val();
        priceseason=$('#PriceSeasonId option:selected').val();

        $('#dayprice_form_price_group').attr({value:pricegroup});
        $('#dayprice_form_price_season').attr({value:priceseason});
        $('#dayprice_form_price_group_day').attr({value:pricegroup});
        $('#dayprice_form_price_season_day').attr({value:priceseason});

    var data = $(form_id).formSerialize();

    //callbackfunction price_save_season_success (js)
    $.post(ALIASPATH + '/admin/prices/form_save/'+chooser, data, preise_holen,'json');
}

function price_save_standardprice_hour()
{
        var form_id='#form_price_add_standardprice_hour';

        //form data prepared
        chooser='standard';
        pricegroup=$('#PricePriceGroupId option:selected').attr('value');
        priceseason=$('#PriceSeasonId option:selected').attr('value');

        //alert('group:'+pricegroup+'  season'+priceseason);

        $('#standardprice_hour_form_price_group').attr({value:pricegroup});
        $('#standardprice_hour_form_price_season').attr({value:priceseason});

        var Price=$('#standardprice_hour_form_price').val();
        var num_checker= Price*1;

                if(Price.length<1 || isNaN(num_checker))
                {
                        $('#standardprice_hour_form_price').addClass('error_border');
                        return false;
                }
                else
                {
                        $('#standardprice_hour_form_price').removeClass('error_border');
                }


        activity_indicator_start();
    var data = $(form_id).formSerialize();

    $.post(ALIASPATH + '/admin/prices/form_save/'+chooser, data, standardprice_hour_saved,'json');
}

function standardprice_hour_saved(data)
{
        //debugger;
        $('#standardprice_hour_form_price_id').attr({value:data.result.id});
        $('#flashMessage').hide();
        $('#flashMessage').html(gespeichert);
        $('#flashMessage').fadeIn("slow");

        if(data.result.end.min.length<2)
        {
                data.result.end.min='0'+data.result.end.min;
        }
        if(data.result.start.min.length<2)
        {
                data.result.start.min='0'+data.result.start.min;
        }

        //alert(data.result.end.hour);
        $('#standardprice_option_'+data.result.id).remove();
        new_option='<option value='+data.result.id+' id="standardprice_option_'+data.result.id+'" endtime="'+data.result.end.hour+':'+data.result.end.min+':00" starttime="'+data.result.start.hour+':'+data.result.start.min+':00" starthour='+data.result.start.hour+' startmin='+data.result.start.min+' endhour='+data.result.end.hour+' endmin='+data.result.end.min+' describer=standard price='+data.result.price+' selected="selected">'+data.result.start.hour+':'+data.result.start.min+':00-'+data.result.end.hour+':'+data.result.end.min+':00</option>';
        $('#standardprice_selectbox').prepend(new_option);
        $('#standardprice_selectbox').show();
        $('#standardprice_hour_select_dayprice').show();

        //change_standardprice_select();
        activity_indicator_stop();
        //standardprice_selectbox();
}
function standardprice_hour()
{
        chooser='standard';
        pricegroup=$('#PricePriceGroupId option:selected').attr('value');
        priceseason=$('#PriceSeasonId option:selected').attr('value');

        $.post(ALIASPATH + '/admin/prices/get_prices/'+priceseason+'/'+pricegroup+'/'+chooser, {}, standardprice_hour_success,'json');
}

function standardprice_hour_success(data)
{
        for(i in data.result.Price)
                {
                        //alert(i);
                }
}

function preise_holen()
{
        pricegroup=$('#PricePriceGroupId option:selected').val();
        priceseason=$('#PriceSeasonId option:selected').val();
        $.post(ALIASPATH + '/admin/prices/get_prices/'+priceseason+'/'+pricegroup+'/', {}, preise_holen_sucess,'json');
}

function preise_holen_sucess(data)
{
        //debugger;
        wochentage=new Array();
        wochentage['Mo']='#calendar_MO .calendar_dayprice';
        wochentage['Di']='#calendar_DI .calendar_dayprice';
        wochentage['Mi']='#calendar_MI .calendar_dayprice';
        wochentage['Do']='#calendar_DO .calendar_dayprice';
        wochentage['Fr']='#calendar_FR .calendar_dayprice';
        wochentage['Sa']='#calendar_SA .calendar_dayprice';
        wochentage['So']='#calendar_SO .calendar_dayprice';


        if(typeof(data.result)=='object')
        {
                if(!typeof(data.result.standard)=='undefined')
                {
                        $('#standardprice_day_row #PricePrice').attr({value:data.result.standard.Price.price});
                        $('#standard_form_price_id').attr({value:data.result.standard.Price.id});
                        $('.calendar_dayprice').html(data.result.standard.Price.price);
                }
                else
                {
                        $('.calendar_dayprice').html('XXX');
                }

                bool=false;
                bool_fixed=false;

                dayprice_array= new Array();
                for(i in data.result)
                {
                        if(     data.result[i].Price.describer=='standard' &&
                                data.result[i].Price.price_unit=='86400' &&
                                data.result[i].Price.endtime=='00:00:00'
                                )
                        {
                                standard_price= data.result[i].Price.price;
                                standard_id=data.result[i].Price.id;
                                bool=true;
                        }

                        if(wochentage[data.result[i].Price.describer]!=undefined && data.result[i].Price.price_unit=='86400' &&  data.result[i].Price.endtime=='00:00:00')
                        {
                                html_cell=wochentage[data.result[i].Price.describer];
                                dayprice_array[i]= new Object();
                                dayprice_array[i]["cell"]=html_cell;
                                dayprice_array[i]["price"]=data.result[i].Price.price;
                        }

                        //pauschalpreis
                        if(     data.result[i].Price.describer=='standard' &&
                                data.result[i].Price.price_unit=='0' &&
                                data.result[i].Price.price_duration=='0'
                                )
                        {
                                standard_price= data.result[i].Price.price;
                                standard_id=data.result[i].Price.id;
                                bool=true;
                        }


                        else
                        {

                        }

                }
                if(bool)
                {
                        $('#standardprice_day_row #PricePrice').val(standard_price);
                        $('#standard_form_price_id').val(standard_id);
                        $('.calendar_dayprice').html(standard_price);
                }

                for ( x in dayprice_array) {
                        html_cell=dayprice_array[x]['cell'];
                        $(html_cell).html(dayprice_array[x]['price']);
                }
                //dayprice_selectbox();
                dayprice_selectbox_sucess(data);
                standardprice_selectbox_sucess(data);
        }
        else
        {
                //testen ob wir jemals in dieses else kommen (!)
                $('#PricePrice').attr({value:''});
                $('#standard_form_price_id').attr({value:''});
                //$('.calendar_dayprice').html('XXX');

                activity_indicator_stop();
        }
}

function day_preise_holen()
{
        chooser=$('#dayprice_chooser').val();
        pricegroup=$('#PricePriceGroupId option:selected').val();
        priceseason=$('#PriceSeasonId option:selected').val();

        $.post(ALIASPATH + '/admin/prices/get_prices/'+priceseason+'/'+pricegroup+'/'+chooser, {}, day_preise_holen_sucess,'json');
}

function day_preise_holen_sucess(data)
{
        //debugger;
        if(typeof(data.result)=='object' && typeof(data.result.Price)=='object')
        {
                $('#form_price_add_dayprice_day #PricePrice').attr({value:data.result.Price.price});
                $('#dayprice_form_price_id_day').attr({value:data.result.Price.id});
                $('#form_price_add_dayprice #dayprice_form_starttime').attr({value:data.result.Price.starttime});
                $('#form_price_add_dayprice #dayprice_form_endtime').attr({value:data.result.Price.endtime});
        }
        else
        {

                $('#form_price_add_dayprice #PricePrice').attr({value:''});
                $('#form_price_add_dayprice_day #PricePrice').attr({value:''});
                $('#dayprice_form_price_id').attr({value:''});
                $('#form_price_add_dayprice #dayprice_form_starttime').attr({value:''});
                $('#form_price_add_dayprice #dayprice_form_endtime').attr({value:''});
                $('.calendar_dayprice').html('XXX');
        }
}

function show_standardprice_time_form()
{
        if($('#show_standardprice_time').attr('checked')==true)
        {
                $('#form_price_add_standardprice_hour').show();
                $('#standardprice_day_row').hide();
                $('#show_standardprice_time').attr({checked:'checked'});

                //Umschalten von Tag auf stundenweise
                standardprice_selectbox();
        }
        else
        {
                $('#form_price_add_standardprice_hour').hide();
                $('#standardprice_day_row').show();
                $('#show_standardprice_time').removeAttr('checked');
                $('#standardprice_hour_select_dayprice').hide();
        }
}

function show_dayprice_time_form()
{
        if($('#show_dayprice_time').attr('checked')==true)
        {
                $('.dayprice_times').show();
                $('#dayprice_save_buttom_1').hide();
                $('#show_dayprice_time').attr({checked:'checked'});
                //Umschalten von Tag auf stundenweise
                $('#dayprice_form_price_unit').attr({value:'3600'})
                dayprice_selectbox();
                $('#form_price_add_dayprice_day #PricePrice').hide();
                $('#form_price_add_dayprice #PricePrice_hour').show();
                $('#dayprice_select_dayprice').show();
        }
        else
        {
                $('.dayprice_times').hide();
                $('#dayprice_save_buttom_1').show();
                $('#form_price_add_dayprice_day #PricePrice').show();
                $('#form_price_add_dayprice #PricePrice_hour').hide();
                $('#show_dayprice_time').removeAttr('checked');
                $('#dayprice_form_price_unit').attr({value:'86400'})
                $('#dayprice_select_dayprice').hide();
        }

}

function standardprice_selectbox(){
/*
        chooser='standard';
        pricegroup=$('#PricePriceGroupId option:selected').attr('value');
        priceseason=$('#PriceSeasonId option:selected').attr('value');

        $.post(ALIASPATH + '/admin/prices/get_prices/'+priceseason+'/'+pricegroup+'/'+chooser+'/true', {}, standardprice_selectbox_sucess,'json');
*/
}

function standardprice_selectbox_sucess(data)
{
        var select_option='';
        var actual_price=$('#standardprice_hour_form_price_id').attr('value');
        var display = false;

        if(typeof(data.result)=='object')
        {
                for(i in data.result)
                {
                        price_id=data.result[i].Price.id;
                        price_start=data.result[i].Price.starttime;
                        price_end=data.result[i].Price.endtime;
                        price_price=data.result[i].Price.price;
                        price_describer=data.result[i].Price.describer;
                        price_unit=data.result[i].Price.price_unit;

                        var split_start=price_start.split(':');
                        var split_end=price_end.split(':');


                        var selected='';

                        if(actual_price==price_id)
                        {
                        selected=' selected="selected" ';
                        }
                        if(price_unit=='3600')
                        {
                                new_option='<option value='+price_id+' id="standardprice_option_'+price_id+'" starttime='+price_start+' endtime='+price_end+' starthour='+split_start[0]+' startmin='+split_start[1]+' endhour='+split_end[0]+' endmin='+split_end[1]+' describer='+price_describer+' price='+price_price+' '+selected+' >'+price_start+'-'+price_end+'</option>';
                                select_option=select_option+new_option;

                                display = true;
                        }
                }

                select_option=select_option+'<option value="add">neu anlegen</option>';
                var selectbox='<select id="standardprice_selectbox" onChange="javascript:change_standardprice_select();">'+select_option+'</select>';

                $('#standardprice_hour_select_dayprice').html(selectbox);

                change_standardprice_select();

                if(! display){
                        $('#standardprice_hour_select_dayprice').hide();
                }
                else{
                        $('#standardprice_hour_select_dayprice').show();
                }

        }
}

function dayprice_selectbox()
{
        chooser=$('#dayprice_chooser').val();
        pricegroup=$('#PricePriceGroupId option:selected').val();
        priceseason=$('#PriceSeasonId option:selected').val();

        $.post(ALIASPATH + '/admin/prices/get_prices/'+priceseason+'/'+pricegroup+'/'+chooser+'/true', {}, dayprice_selectbox_sucess,'json');
}

function dayprice_selectbox_sucess(data)
{
        var select_option='';
        var actual_price=$('#dayprice_form_price_id').attr('value');

        if(typeof(data.result)=='object')
        {
                for(i in data.result)
                {
                        price_id=data.result[i].Price.id;
                        price_start=data.result[i].Price.starttime;
                        price_end=data.result[i].Price.endtime;
                        price_price=data.result[i].Price.price;
                        price_describer=data.result[i].Price.describer;
                        price_unit=data.result[i].Price.price_unit;

                        var selected='';

                        if(actual_price==price_id)
                        {
                        selected=' selected="selected" ';
                        }

                        if(price_end!='00:00:00' && price_unit=='3600')
                        {
                        new_option='<option value='+price_id+' id="dayprice_option_'+price_id+'" starttime='+price_start+' endtime='+price_end+' describer='+price_describer+' price='+price_price+' '+selected+' >'+price_start+'-'+price_end+'</option>';
                        select_option=select_option+new_option;
                        }
                }
                select_option=select_option+'<option value="add">neu anlegen</option>';
                var selectbox='<select id="dayprice_selectbox" onChange="javascript:change_dayprice_select(this);">'+select_option+'</select>';

                $('#dayprice_select_dayprice').html(selectbox);
                change_dayprice_select();
        }
}

function change_dayprice_select()
{       $('#flashMessage').hide();

        //anlegen eines stundenbasierten preises
        if($('#dayprice_selectbox option:selected').attr('value')=='add')
        {
                $('#form_price_add_dayprice #PricePrice_hour').attr({value:''});
                $('#dayprice_form_price_id').attr({value:''});
                $('#dayprice_form_starttime').attr({value:''});
                $('#dayprice_form_endtime').attr({value:''});

                //dayprice_form_starttime
                activity_indicator_stop();
        }
        // vorhandene werte einfuegen
        else
        {
                starttime=$('#dayprice_selectbox option:selected').attr('starttime');
                endtime=$('#dayprice_selectbox option:selected').attr('endtime');
                price=$('#dayprice_selectbox option:selected').attr('price');
                describer=$('#dayprice_selectbox option:selected').attr('describer');
                id=$('#dayprice_selectbox option:selected').attr('value')

                $('#form_price_add_dayprice #PricePrice_hour').attr({value:price});
                $('#dayprice_form_price_id').attr({value:id});
                $('#dayprice_form_starttime').attr({value:starttime});
                $('#dayprice_form_endtime').attr({value:endtime});

                activity_indicator_stop();
        }
}

function change_standardprice_select()
{
        $('#flashMessage').hide();
        //anlegen eines stundenbasierten preises
        if($('#standardprice_selectbox option:selected').val()=='add')
        {
                $('#standardprice_hour_form_price').val('');
                $('#standardprice_hour_form_price_id').val('');
                $('#PriceStarttimeHour').val('00');
                $('#PriceStarttimeMin').val('00');
                $('#PriceEndtimeHour').val('00');
                $('#PriceEndtimeMin').val('00');
                //l�schen button verstecken
                $('#delete_rabatt').hide();

                activity_indicator_stop();
        }
        // vorhandene werte einfuegen
        else
        {
                //debugger;
                //hier nach dem essen weiter variablen fuellen (!!!)
                starttime=$('#standardprice_selectbox option:selected').attr('starttime');
                starthour=$('#standardprice_selectbox option:selected').attr('starthour');
                startmin=$('#standardprice_selectbox option:selected').attr('startmin');
                endtime=$('#standardprice_selectbox option:selected').attr('endtime');
                endhour=$('#standardprice_selectbox option:selected').attr('endhour');
                endmin=$('#standardprice_selectbox option:selected').attr('endmin');

                price=$('#standardprice_selectbox option:selected').attr('price');
                describer=$('#standardprice_selectbox option:selected').attr('describer');
                id=$('#standardprice_selectbox option:selected').val();

                //l�schen button einblenden
                $('#delete_rabatt').show();

                $('#standardprice_hour_form_price').attr({value:price});
                $('#standardprice_hour_form_price_id').attr({value:id});
                //$('#standardprice_hour_form_starttime').attr({value:starttime});
                //$('#standardprice_hour_form_endtime').attr({value:endtime});
                $('#PriceStarttimeHour').val(starthour);
                $('#PriceStarttimeMin').val(startmin);
                $('#PriceEndtimeHour').val(endhour);
                $('#PriceEndtimeMin').val(endmin);


                activity_indicator_stop();
        }
}

function rabatte_selectbox()
{
        $('#flashMessage').hide();

        var rt_name=$('#RessourcetypeId option:selected').text();
        var res_id=$('#RessourceId option:selected').attr('value');
                if(!res_id || res_id=='add' || res_id=='0') res_name='<i>'+all+'</i>';
                else res_name=$('#RessourceId option:selected').text();
        var season_name=$('#PriceSeasonId option:selected').text();

        //Fuellen der Anzeigedaten
        $('#price_calendar_head_ressourcetype').html(rt_name);
        $('#price_calendar_head_ressource').html(res_name);
        $('#price_calendar_head_season').html(season_name);

        price_group=$('#PricePriceGroupId option:selected').attr('value');
        price_season=$('#PriceSeasonId option:selected').attr('value');

        $.post(ALIASPATH + '/admin/prices/get_rabatte/'+price_season+'/'+price_group, {}, rabatte_selectbox_sucess,'json');
}

function rabatte_selectbox_sucess(data)
{
        //debugger;
        var select_option='';
        var actual_price=$('#dayprice_form_price_id').attr('value');

        if(typeof(data.result)=='object')
        {
                for(i in data.result)
                {
                        if(typeof(data.result[i].Price[0])=='object')
                        {
                        rabatt_id=data.result[i].AddField.id;
                        real_rabatt_id=data.result[i].Price[0].id;
                        rabatt_name=data.result[i].AddField.name;

                        var selected='';

                        new_option='<option add='+rabatt_id+' value='+real_rabatt_id+' id="rabatt_option_'+real_rabatt_id+'" '+selected+' >'+rabatt_name+'</option>';
                        select_option=select_option+new_option;
                        }
                }

                select_option=select_option+'<option value="add">neu anlegen</option>';
                var selectbox='<select name="data[Price][addfiel_id]" id="rabatt_selectbox" onChange="javascript:change_rabatt_select();">'+select_option+'</select>';

                $('#rabatt_select_dayprice').html(selectbox);
                change_rabatt_select();
        }
}

function change_rabatt_select()
{
        $('#flashMessage').hide();

        if($('#rabatt_selectbox option:selected').attr('value')=='add')
        {
                $('#rabattprice_addfield').val('');
                $('#rabattprice_addfield').show();
                //$('#delete_rabatt').hide();
                $('#rabatte_special_day').hide();
                $('#rabatte_every_day').hide();

                $(".closebutton").hide();
                $(".openbutton").show();

                $('#rabattprice_form_starttime').val('');
                $('#rabattprice_form_endtime').val('');
                $('#form_price_rabatte #PricePrice').val('');
                $('#form_price_rabatte #PricePriceDuration').val('');
                $('#starttimeHour').val('00');
                $('#starttimeMin').val('00');
                $('#endtimeHour').val('00');
                $('#endtimeMin').val('00');

                $('#rabatt_form_price_id').val('');
                $('#form_price_rabatte #addfield_id').val('');

                $('#form_price_rabatte #PriceDescriber option').removeAttr('selected');
                $('#form_price_rabatte #PricePriceUnit option').removeAttr('selected');
        }
        // vorhandene werte einfuegen
        else
        {
                pricegroup=$('#PricePriceGroupId option:selected').val();
                priceseason=$('#PriceSeasonId option:selected').val();
                addfield=$('#rabatt_selectbox option:selected').attr('add');

                $('#rabattprice_addfield').hide();
                $('#delete_rabatt').show();
                var rabatt_id= $('#rabatt_selectbox option:selected').val();
                var add_id= $('#rabatt_selectbox option:selected').attr('add');
                $('#delete_rabatt a').attr({href:'/motoloco/admin/prices/delete/'+rabatt_id+'/'+add_id});

                $.post(ALIASPATH + '/admin/prices/get_single_rabatt/'+priceseason+'/'+pricegroup+'/'+addfield, change_rabatt_select_sucess, {},'json');
        }
}

function change_rabatt_select_sucess(data)
{
        $('#rabatte_special_day').hide();
        $('#rabatte_every_day').hide();

        if(typeof(data.result)=='object' && typeof(data.result.Price)=='object')
        {
                price_id=data.result.Price.id;
                addfield_id=data.result.Price.addfields_id;
                price=data.result.Price.price;
                price_unit=data.result.Price.price_unit;
                price_duration=data.result.Price.price_duration;
                describer=data.result.Price.describer;
                starttime=data.result.Price.starttime;
                endtime=data.result.Price.endtime;
                starthour=data.result.starttime.hour;
                startmin=data.result.starttime.min;
                endhour=data.result.endtime.hour;
                endmin=data.result.endtime.min;


                if(describer=='standard')
                {
                        $('#form_price_rabatte #PriceDescriber_new').val(describer);
                        endday='standard';
                }
                else
                {
                endday=data.result.endday;
                }
                $('#rabattprice_form_starttime').val(starttime);
                $('#rabattprice_form_endtime').val(endtime);
                $('#form_price_rabatte #PricePrice').val(price);
                $('#form_price_rabatte #PricePriceDuration').val(price_duration);

                $('#form_price_rabatte #PriceDescriber').val(describer);
                $('#form_price_rabatte #PriceDescriber_new').val(describer);
                $('#form_price_rabatte #PriceDescriber_to').val(endday);
                $('#form_price_rabatte #PricePriceUnit').val(price_unit);
                $('#rabatt_form_price_id').val(price_id);
                $('#form_price_rabatte #addfield_id').val(addfield_id);

                $('#PriceStarttimeHour').val(starthour);
                $('#PriceStarttimeMin').val(startmin);
                $('#PriceEndtimeHour').val(endhour);
                $('#PriceEndtimeMin').val(endmin);
        }
        else
        {
                $('#form_price_rabatte #PriceDescriber option').removeAttr('selected');
                $('#form_price_rabatte #PricePriceUnit option').removeAttr('selected');
        }
}

function price_save_rabatt()
{       activity_indicator_start();
        var form_id='#form_price_rabatte';
        //form data prepared
        pricegroup=$('#PricePriceGroupId option:selected').attr('value');
        priceseason=$('#PriceSeasonId option:selected').attr('value');
        chooser=$(form_id +' #PriceDescriber option:selected').attr('value');
        price_unit=$(form_id +' #PricePriceUnit option:selected').attr('value');
        price_duration=$(form_id +' #PricePriceUnit option:selected').attr('value');

        addfield_id=$(form_id +' #PriceAddfielId option:selected').attr('value');

        $('#rabatt_form_price_group').attr({value:pricegroup});
        $('#rabatt_form_price_season').attr({value:priceseason});

        if($('#rabattprice_addfield').attr('value')!='undefined' && $('#PricePrice').attr('value')!='undefined')
        {
        var data = $(form_id).formSerialize();
        //callbackfunction price_save_season_success (js)
        $.post(ALIASPATH + '/admin/prices/form_save/'+chooser, data, price_save_rabatt_sucess,'json');
        }
}

function price_save_rabatt_sucess(data)
{
        var form_id='#form_price_rabatte';

        add=data.result.addfield_id;
        rabatt_name=$('#rabattprice_addfield').attr('value');
        selected='selected';
        rabatt_id=data.result.id;
        new_option='<option value='+rabatt_id+' id="rabatt_option_'+rabatt_id+'" '+selected+' add="'+add+'">'+rabatt_name+'</option>';
        addfield_id=$(form_id +' #rabatt_selectbox option:selected').attr('value');

        $('#flashMessage').hide();
        $('#flashMessage').html(gespeichert);
        $('#flashMessage').fadeIn("slow");

        if(addfield_id=='add')
        $("#rabatt_selectbox").prepend(new_option);
        $('#rabattprice_addfield').hide();

        $('#delete_rabatt').show();
        $('#delete_rabatt a').attr({href:'/motoloco/admin/prices/delete/'+rabatt_id+'/'+add});

        activity_indicator_stop();
}

function synchronize_rabatt(select_id, synchronize_id)
{
        sync_class=$('#'+select_id+' option:selected').attr('class');
        $('.'+sync_class).attr({selected:'selected'});
        if(select_id=='PriceDescriber_new')
        {
                $('#PricePriceDuration').val('');
        }
}

function calculate_day_distance()
{
        Distance = new Array('option_Mo','option_Di' , 'option_Mi' ,'option_Do', 'option_Fr', 'option_Sa', 'option_So', 'option_Mo','option_Di' , 'option_Mi' ,'option_Do', 'option_Fr', 'option_Sa', 'option_So');
        var bool_test=false;
        var dummy=0;

        startday=$('#PriceDescriber option:selected').attr('class');
        endday=$('#PriceDescriber_to option:selected').attr('class');


        if(startday==endday) dummy=0;
        else
        {
                for (var i = 0; i < Distance.length; ++i)
                {
                act = Distance[i];

                if(startday==act)
                        {
                                bool_test=true;
                                startday='xxx';
                        }

                if(bool_test)
                        {
                                if(endday==act) bool_test=false;
                                else dummy++;

                        }
                }
        }

        starttime_hour=$('#PriceStarttimeHour  option:selected').val();
        starttime_min=$('#PriceStarttimeMin  option:selected').val();

        endtime_hour=$('#PriceEndtimeHour  option:selected').val();
        endtime_min=$('#PriceEndtimeMin  option:selected').val();

        //alert('start: '+starttime_hour+' / end: '+endtime_hour);
        //wir rechnen in Minuten um
        rechenknecht_day=dummy*24*60;
        rechenknecht_hour=endtime_hour-starttime_hour;
        rechenknecht_hour=rechenknecht_hour*60;
        rechenknecht_min=endtime_min-starttime_min;

        rechenknecht_total=rechenknecht_day+rechenknecht_hour+rechenknecht_min;

        $('#PricePriceUnit').val('60');
        $('#PricePriceDuration').val(rechenknecht_total);
}

function synchronize_times(source,destination)
{
        source_hour=$('#Price'+source+'Hour  option:selected').val();
        source_min=$('#Price'+source+'Min  option:selected').val();

        date=source_hour+':'+source_min+':00';
        $('#'+destination).val(date);
}

function rabatt_opener(chooser)
{
        $('#flashMessage').hide();
        switch(chooser){
                case 'open':
                                        $("#rabattview_1 .openbutton").hide();
                                        $("#rabattview_1 .closebutton").show();
                                        $("#rabatte_special_day").show();
                                        $("#rabatte_special_day div").show();
                                        $("#rabatte_every_day").hide();
                                        $("#rabattview_2 .closebutton").hide();
                                        $("#rabattview_2 .openbutton").show();
                                        break;
        case 'close':
                                        $("#rabattview_1 .closebutton").hide();
                                        $("#rabattview_1 .openbutton").show();
                                        $("#rabatte_special_day").hide();
                                        $("#rabatte_special_day div").hide();
                                        break;

        case 'open_duration':
                                        //Daten vorbereiten
                                        $('#starttimeHour').val('00');
                                        $('#starttimeMin').val('00');
                                        $('#endtimeHour').val('00');
                                        $('#endtimeMin').val('00');
                                        $('#rabattprice_form_endtime').val('00:00:00');
                                        $('#rabattprice_form_starttime').val('00:00:00');
                                        // Buttons wechseln & einblenden
                                        $("#rabattview_2 .openbutton").hide();
                                        $("#rabattview_2 .closebutton").show();
                                        $("#rabatte_every_day").show();
                                        $("#rabatte_every_day div").show();

                                        // ausblenden der nicht benoetigten maske
                                        $("#rabatte_special_day").hide();
                                        $("#rabattview_1 .closebutton").hide();
                                        $("#rabattview_1 .openbutton").show();
                                        break;

        case 'close_duration':
                                        $("#rabattview_2 .closebutton").hide();
                                        $("#rabattview_2 .openbutton").show();
                                        $("#rabatte_every_day").hide();
                                        $("#rabatte_every_day div").hide();
                                        break;
        }
}

function delete_price(id)
{
        $.post(ALIASPATH + '/admin/prices/delete/'+id, {}, delete_price_success(id),'json');
        return false;
}

function delete_price_success(id)
{
        $('#AjaxMessage').html(del_message);
        $('#AjaxMessage').fadeIn('slow');
        $('#AjaxMessage').animate({opacity: 1.0}, 5000);
        $('#AjaxMessage').fadeOut('slow');


        $('#row_'+id).remove();
        price_counter=$('.table tr').length;

        if(price_counter < 2){
                rt=getUrlParam('rt');
                res=getUrlParam('res');
                link=ALIASPATH + '/admin/prices/index/pg:0/rt:'+rt+'/res:'+res;
                location.href=link;
        }
        return false;
}

function delete_rabatt()
{       activity_indicator_start();
        rabatt_id=$('#rabatt_selectbox option:selected').val();
        add_id=$('#rabatt_selectbox option:selected').attr('add');

        $.post(ALIASPATH + '/admin/prices/delete/'+rabatt_id+'/'+add_id, {}, delete_rabatt_success,'json');
        return false;
}

function delete_rabatt_success(data)
{
        optionname='#rabatt_option_'+data.result.id;

        $(optionname).hide();
        $(optionname).removeAttr('selected');
        //form leeren
        $('#rabattprice_form_starttime').attr({value:''});
        $('#rabattprice_form_endtime').attr({value:''});
        $('#form_price_rabatte #PricePrice').attr({value:''});
        $('#form_price_rabatte #PricePriceDuration').attr({value:''});
        $('#rabatt_form_price_id').attr({value:''});
        $('#form_price_rabatte #addfield_id').attr({value:''});
        $('#rabattprice_addfield').attr({value:''});
        //ein- & ausblenden
                $('#rabattprice_addfield').show();
                $('#delete_rabatt').hide();
                $('#rabatte_special_day').hide();
                $('#rabatte_every_day').hide();

        $('#rabatt_selectbox option').attr({selected:'selected'});
        activity_indicator_stop();
}

function delete_standard_dayprice()
{       activity_indicator_start();
        $('#PricePriceGroupId option:selected').val('0');
        rabatt_id=$('#standard_form_price_id').val();
        $.post(ALIASPATH + '/admin/prices/delete/'+rabatt_id+'/', {}, delete_standard_dayprice_success,'json');
        return false;
}

function delete_standard_dayprice_success()
{
        $('#standard_form_price_id').val('');
        $('#PricePrice').val('');
        $('.calendar_dayprice').html('xx');
        preise_holen();
}

function delete_dayprice()
{       activity_indicator_start();
        id=$('#dayprice_form_price_id_day').val();
        $.post(ALIASPATH + '/admin/prices/delete/'+id+'/', {}, delete_dayprice_success,'json');
        return false;
}

function delete_dayprice_success()
{
        describer=$('#dayprice_chooser_day').val();
        standardpreis=$('#standardprice_day_row #PricePrice').val();

        translation_array= new Array();
        translation_array['Mo']='calendar_MO';
        translation_array['Di']='calendar_DI';
        translation_array['Mi']='calendar_Mi';
        translation_array['Do']='calendar_DO';
        translation_array['Fr']='calendar_FR';
        translation_array['Sa']='calendar_SA';
        translation_array['So']='calendar_SO';

        update_row='#'+translation_array[describer];
        $('#form_price_add_dayprice_day #PricePrice').val('');
        $('#form_price_add_dayprice_day #dayprice_form_price_id_day').val('');
        $(update_row+' .calendar_dayprice').html(standardpreis);
        activity_indicator_stop();
}

function delete_hourprice()
{       activity_indicator_start();
        id=$('#standardprice_selectbox option:selected').val();
                $.post(ALIASPATH + '/admin/prices/delete/'+id+'/', {}, delete_hourprice_success,'json');
        return false;
}

function delete_hourprice_success()
{
        $('#standardprice_hour_form_price').val('');
        $('#standardprice_hour_form_price_id').val('');
        $('#standardprice_hour_form_starttime').val('');
        $('#standardprice_hour_form_endtime').val('');
        $('#standardprice_selectbox option:selected').remove();
        change_standardprice_select();
}

function goto_manage(selector)
{
        switch(selector)
        {
                case 'dayprice':        redirect='/admin/prices/manage_dayprice/'
                                                        break;
                case 'hourprice':       redirect='/admin/prices/manage_hourprice/'
                                                        break;
                case 'rabatte':         redirect='/admin/prices/manage_rabatte/'
                                                        break;
        }
        var rt=$('#RessourcetypeId option:selected').val();
        var res=$('#RessourceId option:selected').val();

        if (rt<1 || rt=='add')
        {
                top.location=ALIASPATH +redirect;
        }

        if (res<1 || res=='add')
        {
                top.location=ALIASPATH +redirect+rt;
        }
        else top.location=ALIASPATH +redirect+rt+'/'+res;
}

function activity_indicator_start()
{
        // evt noch vorhandene loader raushauen
        $('.ajaxloader').remove();
        $('div.submit').hide();
        $('.submitbutton').hide();
        $('.submit').after("<img class=\"ajaxloader\" alt= \"Ajax loader\" src="+ ALIASPATH + "/img/loader_arrows.gif>");
        //$('.save_button b').hide();
        //$('.save_button b').after("<img class=\"ajaxloader\" alt= \"Ajax loader\" src=" + ALIASPATH + "/img/loader_arrows.gif>");
}

function activity_indicator_stop()
{
        $('.ajaxloader').remove();
        $('.submit').show();
        $('.submitbutton').show();
        //$('.save_button b').show();
}

function addfield_help(help_id)
{
        $('.helpmessage').hide();
        $('#'+help_id).show();
}

function change_input_type()
{
        who=$('#AddFieldOption option:selected').val();
        switch(who)
        {
                case 'select':  $('.addfieldoptions_table').show();
                                                $('.addfieldoptions_table .option_content').hide();
                                                $('.addfieldoptions_table .optionname').show();
                                                        break;
                default:                $('.addfieldoptions_table').hide();
                                                        break;
        }
}

function changeAddFieldOption(id)
{
        if(id=='new')
        {}
        else
        {
                id=parseInt(id);
        }
        unit_obj='#AddFieldOption_unit_'+id;
        duration_obj='#AddFieldOption_duration_'+id;
        target='#AddFieldOption_value_'+id;
        duration=parseInt($(duration_obj).val());
        unit=parseInt($(unit_obj).val());

        if(unit<99999999 )
        {
                value=duration*unit;
        }
        else
        {
                value='all';
                $(duration_obj).val(0);
        }
        $(target).val(value);
}

function new_add_field_option()
{
        options_array= new Array();
        options_array[0]='.addfieldoption_new';
        options_array[1]='.addfieldoption_new_1';
        options_array[2]='.addfieldoption_new_2';
        options_array[3]='.addfieldoption_new_3';
        options_array[4]='.addfieldoption_new_4';
        options_array[5]='.addfieldoption_new_5';
        options_array[6]='.addfieldoption_new_6';
        options_array[7]='.addfieldoption_new_7';
        options_array[8]='.addfieldoption_new_8';
        options_array[9]='.addfieldoption_new_9';

        for (var i = 0; i < options_array.length; ++i)
                {
                        act = options_array[i];
                        if($(act).attr('style')=='display: none;')
                        {
                                $(act).show();
                                return true;
                        }
                }
        $("#add_button").hide();
}

function show_addfieldoptions(target)
{
        $('.upbutton').hide();
        $('.downbutton').show();
        $('.'+target+' .upbutton').show();
        $('.'+target+' .downbutton').hide();
        $('.addfieldoptions_table .option_content').hide();
        $('.addfieldoptions_table .optionname').show();
        $('.addfieldoptions_table .'+target+' .option_content').show();
        $('#flashMessage').hide();
}

function clip_addfieldoptions()
{
        $('.addfieldoptions_table .option_content').hide();
        $('.upbutton').hide();
        $('.downbutton').show();
        $('#flashMessage').hide();
}

function hide_new_options()
{
        $(".addfieldoption_new").hide();
        $(".addfieldoption_new_1").hide();
        $(".addfieldoption_new_2").hide();
        $(".addfieldoption_new_3").hide();
        $(".addfieldoption_new_4").hide();
        $(".addfieldoption_new_5").hide();
        $(".addfieldoption_new_6").hide();
        $(".addfieldoption_new_7").hide();
        $(".addfieldoption_new_8").hide();
        $(".addfieldoption_new_9").hide();
}

/*****************************
/ @name: disable_menu()
/ @author: Jens Krause
/ @date: Nov. 2008
/ @description:  - disables to click around in the menu of the BE
/ @used: in some steps (f.e. default_wizzard_XX) the user shouldn't
/ be able to leave the views without saving. that's for!
*****************************/
function disable_menu()
{
        $('#BreadCrumbs').hide();
        $("#dropdown_nav a").removeAttr("href");
        $("#reserved_ressources_div img").removeAttr("onClick");
        $("#reservation_search_input").attr({disabled:'DISABLED'});
}

function paytype_fade()
{

        if($('#paytype_transfer').attr('checked')==true)
        {
                $('#transfer div').fadeTo("slow", 1);
                $('#direct_debit div').fadeTo("slow", 0.5);

        }
        else
        {
                if($('#paytype_direct_debit').attr('checked')==true)
                {
                        $('#transfer div').fadeTo("slow", 0.5);
                        $('#direct_debit div').fadeTo("slow", 1);
                }
        }
}

function payment_switch(id){
        if($(id+'_checker .checker').attr('checked')==true)
                {
                        $(id).show();
                }
        else
                {
                        $(id).hide();
                }
        }

function switch_paytype(array, value)
{
        $('#frontendpaymentoptions_tab').children('div.clearfix').children('.boldtopborder').hide();
        $('#js_stay').show();
        $('#ClientAllowFePayment').val(value);
        for(i=0;i<array.length;i++)
        {
            $("#div_"+array[i]).show();
        }

}

function getUrlParam(strParamName){
//Funktion holt named Parameter aus url
//im Fehlerfall: return false
         url=window.location.href;
         params=url.split(strParamName+':');

         if(params.length>1)
         {
                ptype=params[1];
                ptype_array=ptype.split('/');
                if(ptype_array.length>1)
                {
                        ptype=ptype_array[0];
                }

         }
         else return false;

         return ptype;
}

function price_filter()
{
        ptype=getUrlParam('ptype');

        saison=$('#saison_search option:selected').val();
        pg=$('#pg_search option:selected').val();
        describer=$('#describer_search option:selected').val();
        price=$('#price_search option:selected').val();
        unit=$('#unit_search option:selected').val();
        start=$('#starttime_search option:selected').val();
        end=$('#endtime_search option:selected').val();

    var link = ALIASPATH + "/admin/prices/index/"
                            + URLPART
                            + "begintime:" + start
                            + "/endtime:" +  end
                            + "/pg:" +  pg
                                                        + "/saison:"+ saison
                                                        + "/describer:"+ describer
                                                        + "/price:"+ price
                                                        + "/unit:"+unit;
        if(ptype) link=link+"/ptype:"+ptype;
    return link;
    }

function hide_flashmessage(){
        $('#flashMessage').animate({opacity: 1.0}, 5000);
        $('#flashMessage').fadeOut('slow');
    }

function showhelp(param){

    var help_url ='http://localhost/joomla1_5_14/';
    var new_help_url = help_url;
    var act_help_url = $('#iframe_help_message_box').attr('src');
    var current_display = $('#help_message_box').css('display');


    if(!(param==undefined)){
        new_help_url = help_url + '?hash=' + param;
        $('#iframe_help_message_box').attr({src : new_help_url});
    }

    switch (current_display){
        case 'none':
           $('#help_message_box').show();
            break;
        case 'block':
            if(new_help_url == act_help_url){
                $('#help_message_box').hide();
            }
            else{
                $('#help_message_box').hide();
                $('#iframe_help_message_box').attr({src : new_help_url});
                $('#help_message_box').show();
            }
            break;
        default:
            break;
  }
}

 function popup(wintype){
   var nwl = (screen.width-620)/2;
   var nwh = (screen.height-450)/2;
   popUp=window.open(wintype, 'Images', 'toolbar=no,location=no,directories=no,status=no,menubar=yes,scrollbars=yes,resizable=yes,width=620,height=450,left='+nwl+',top='+nwh+'');
   popUp.window.focus();

 }


