var isIE = true;
if(navigator.appName == 'Netscape')
    isIE = false;

var mouseTop  = 0;
var mouseLeft = 0;
document.onmousemove = registerMousePos;

function hoverClass(elem)
{
    if(typeof(elem) != 'object')
        elem = $(elem);

    var cName   = elem.className;
    var cName2  = '';
    var len     = cName.length;

    if(cName == undefined || cName == '')
        return false;

    if(cName.substr((len-3), 3) == '_mo')
        elem.className = cName.substr(0, (len-3));
    else
        elem.className = cName+'_mo';
}
function registerMousePos(e)
{
    if(isIE == false)
    {
       mouseLeft = e.pageX;
       mouseTop = e.pageY;
    }
    else
    {
       mouseLeft = window.event.x;
       mouseTop = window.event.y;
    }
}
function menuMo(el, reset)
{
    var clName = '';

    if(typeof(reset) == 'undefined')
        reset = false;


    if(reset == false && el.className == '')
        clName = 'mo';
    else if(reset == false && el.className == 'akt')
        clName = 'moakt';
    else if(reset == true && el.className == 'mo')
        clName = '';
    else if(reset == true && el.className == 'moakt')
        clName = 'akt';

    el.className = clName;
}

function menuClick(el)
{
    var childs = el.childElements();
    window.location.href = childs[0].href;
    return false;
}

function imageViewer()
{
    this.image = null;
    this.div   = null;
    this.bg    = null;
    this.load  = null;
    
    this.init = function(dir, file, w, h)
    {
        this.iWidth     = w;
        this.iHeight    = h;
        if(this.bg == null)
        {
            this.image = document.createElement('img');
            this.div   = document.createElement('div');
            this.bg    = document.createElement('div');
            this.load  = document.createElement('div');

            this.bg.style.backgroundColor    = '#333333';
            this.bg.style.position           = 'absolute';
            this.bg.style.top                = '0px';
            this.bg.style.left               = '0px';
            this.bg.style.zIndex             = '100';
            this.bg.style.width              = '100%';
            this.bg.style.height             = '100%';
            this.bg.style.textAlign          = 'center';
            this.bg.style.verticalAlign      = 'middle';
            this.bg.style.display            = 'none';

            this.div.style.backgroundColor    = '#ffffff';
            this.div.style.position           = 'absolute';
            this.div.style.zIndex             = '101';
            this.div.style.padding            = '10px';
            this.div.style.border             = '3px solid #333';
            this.div.style.cursor             = 'pointer';
            this.div.style.top                = '10px';
            this.div.style.left               = '10px';
            this.div.style.display            = 'none';

            this.load.style.backgroundColor    = '#ffffff';
            this.load.style.position           = 'absolute';
            this.load.style.zIndex             = '101';
            this.load.style.padding            = '10px';
            this.load.style.border             = '3px solid #333';
            this.load.style.cursor             = 'pointer';
            this.load.style.top                = '100px';
            this.load.style.left               = '100px';
            this.load.style.display            = 'none';
            this.load.style.textAlign          = 'center';
            this.load.innerHTML = 'Bild wird geladen<br><br><br><img src="'+imgDir+'loading_bar.gif" />';
            this.image.style.display          = 'none';

            $('body').appendChild(this.load);
            $('body').appendChild(this.bg);
            if(!isIE)
                this.bg.setOpacity(0.3);
            else
                this.bg.style.filter ="Alpha(opacity=30, finishopacity=0, style=0)";

            this.bg.style.height = $('mainTab').getHeight()+'px';

        }
        var t = getScrollXY();
        this.load.style.top                = ((mouseTop-80)+t[1])+'px';
        this.load.style.left               = (mouseLeft-60)+'px';

        this.bg.style.display          = 'block';
        this.load.style.display        = 'block';
        this.image.src = 'index.php?getImage='+file+'&dir='+dir;
        this.image.onclick = function(){imageView.hide();};
        this.image.onload = function(){window.setTimeout("imageView.show();", 500);};
        this.div.appendChild(this.image);
        $('body').appendChild(this.div);
    };

    this.hide = function()
    {
        this.div.style.display      = 'none';
        this.bg.style.display       = 'none';
        this.image.style.display    = 'none';
    };
    
    this.show = function()
    {
        var myWidth = 0, myHeight = 0;
        if( typeof( window.innerWidth ) == 'number' )
        {
            //Non-IE
            myWidth = window.innerWidth;
            myHeight = window.innerHeight;
        }
        else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
        {
            //IE 6+ in 'standards compliant mode'
            myWidth = document.documentElement.clientWidth;
            myHeight = document.documentElement.clientHeight;
        }
        else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
        {
            //IE 4 compatible
            myWidth = document.body.clientWidth;
            myHeight = document.body.clientHeight;
        }
        
        myWidth -= this.iWidth+26;
        myWidth /= 2;

        myHeight -= this.iHeight+26;
        myHeight /= 2;

        if(myHeight < 10)
            myHeight = 10;
            
        var t = getScrollXY();

        this.div.style.left               = myWidth+'px';
        this.div.style.top                = (myHeight+t[1])+'px';
        this.load.style.display           = 'none';
        this.div.style.display            = 'block';
        this.image.style.display          = 'block';
    }
}
var imageView = new imageViewer;




var scrollAnker_Top     = 1;
var scrollAnker_Speed   = 20;

function scrollToAnker(ankerName)
{
    // Ankerposition
    var top = parseInt(getPositionTop($(ankerName))-20);
    var scroll = getScrollXY();
    scrollAnker_Top  = scroll[1];
    while(scrollAnker_Top+scrollAnker_Speed < top)
    {
        scrollAnker_Top +=scrollAnker_Speed;
        window.setTimeout("window.scrollTo(0,'"+scrollAnker_Top+"')",10);
    }
}

function getScrollXY()
{
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}
function getPositionTop(This)
{
    var el = This;
    var pT = 0;
    while(el)
    {
        pT += el.offsetTop;
        el=el.offsetParent;
    }
    return pT
}


function viewOverlayTemplate(func, tpl, titel, add, width, height, centerScreen)
{
    var param = {};
    if(add != undefined)
    {
        // TODO:    Die abfrage ob ein Array oder ein Objekt vorligt kann raus
        //          wenn alle aufrufe auf Objekte umgestellt wurden
        if(typeof(add[0]) == 'undefined' || typeof(add[0][0]) == 'undefined')
            param = add;
        else
        {
            for(var i=0; i<add.length; i++)
            {
                param[add[i][0]] = add[i][1];
            }
        }
    }

    param['func'] = func;
    param['tpl']  = tpl;

    new Ajax.Request(preDir+'ajax.php', {
        method:     'post',
        parameters: param,
        onSuccess:  function(ret) {
            $('fullPageOverlay_Window_Text').innerHTML = ret.responseText;
            var fo      = $('fullPageOverlay_Window_Text').getElementsBySelector('[focusThis="true"]');
            var bar     = $('fullPageOverlay_Window_Text').innerHTML.indexOf('art="erfolg"');
            var script  = $('fullPageOverlay_Window_Text').getElementsBySelector('[art="script"]');
            
            if(fo[0] != undefined) {
                window.setTimeout("$('"+fo[0].id+"').focus();", 800);
            }
            if(bar > 1) {
                window.setTimeout("hidePageOverlay();", 1800);
            }
            if(script[0] != undefined)
                eval(script[0].innerHTML);
            displayPageOverlay(titel, false, width, height, centerScreen);
        }
    });

}
function displayPageOverlay(titel, onlyFade, width, height, centerScreen)
{
    if(centerScreen == undefined)
        centerScreen = false;

    if(onlyFade == undefined)
        onlyFade = false;

    if(titel == undefined)
        var titel = '';

    $('fullPageOverlay').setOpacity(0);

    if(width == undefined)
        width = 360;
    if(height == undefined)
        height = 350;

    if($('fullPageOverlay_loading').style.display == 'block')
    {
        $('fullPageOverlay_loading_shaddow').fade({duration: 0.1, from: 0.7, to: 0 });
        $('fullPageOverlay_loading').fade({duration: 0.1, from: 0.8, to: 0 });
    }
    $('fullPageOverlay_Window_TitleBar').style.width = width+'px';
    $('fullPageOverlay_Window_TitleBar_Middle').style.width = (width-32)+'px';
    $('fullPageOverlay_Window_Text').style.width = (width-15)+'px';
    $('fullPageOverlay_Window_Text').style.height = (height-30)+'px';
    $('fullPageOverlay_Window').style.width = width+'px';
    $('fullPageOverlay_Window').style.height = height+'px';
    $('fullPageOverlay_Shaddow').style.width = width+'px';
    $('fullPageOverlay_Shaddow').style.height = height+'px';
    if(onlyFade != true)
    {
        $('fullPageOverlay_Window_TitleBar_Middle').innerHTML = titel;
        $('fullPageOverlay_Window').setOpacity(0);
        $('fullPageOverlay_Shaddow').setOpacity(0);
    }

    $('fullPageOverlay').style.display          = 'block';
    if(onlyFade != true)
    {
        $('fullPageOverlay_Window').style.display   = 'block';
        $('fullPageOverlay_Shaddow').style.display  = 'block';

        if(centerScreen == true)
        {
            $('fullPageOverlay_Window').style.marginLeft    = '0px';
            $('fullPageOverlay_Window').style.marginTop     = '0px';
            $('fullPageOverlay_Shaddow').style.marginLeft   = '5px';
            $('fullPageOverlay_Shaddow').style.marginTop    = '5px';
            moveToCenter('fullPageOverlay_Window');
            moveToCenter('fullPageOverlay_Shaddow');
        }
        else
        {
            $('fullPageOverlay_Window').style.top           = '0px';
            $('fullPageOverlay_Window').style.left          = '0px';
            $('fullPageOverlay_Shaddow').style.top          = '0px';
            $('fullPageOverlay_Shaddow').style.left         = '0px';
            $('fullPageOverlay_Window').style.marginLeft    = '150px';
            $('fullPageOverlay_Window').style.marginTop     = '50px';
            $('fullPageOverlay_Shaddow').style.marginLeft   = '155px';
            $('fullPageOverlay_Shaddow').style.marginTop    = '55px';
        }
    }
    $('fullPageOverlay').style.height = $('mainTab').getHeight();
    $('fullPageOverlay').fade({duration: 0.2, from: 0, to: 0.4 });
    if(onlyFade != true)
    {
        $('fullPageOverlay_Window').fade({duration: 0.2, from: 0, to: 1 });
        $('fullPageOverlay_Shaddow').fade({duration: 0.2, from: 0, to: 0.8 });
    }
    else
    {
        if(titel != '' && titel != null && titel != false)
            $('fullPageOverlay_loading').innerHTML      = '<br>'+titel;
        $('fullPageOverlay_loading').style.display  = 'block';
        $('fullPageOverlay_loading').fade({duration: 0.2, from: 0, to: 1 });
        $('fullPageOverlay_loading_shaddow').style.display  = 'block';
        $('fullPageOverlay_loading_shaddow').fade({duration: 0.2, from: 0, to: 1 });
    }
}

function hidePageOverlay(onlyFade)
{
    if(onlyFade == undefined)
        onlyFade = false;

    $('fullPageOverlay').fade({duration: 0.5, from: 0.4, to: 0 });
    if(onlyFade != true)
    {
        $('fullPageOverlay_Window').fade({duration: 0.3, from: 1, to: 0 });
        $('fullPageOverlay_Shaddow').fade({duration: 0.2, from: 0.8, to: 0 });
        window.setTimeout("$('fullPageOverlay').style.display = 'none'; $('fullPageOverlay_Window').style.display = 'none'; $('fullPageOverlay_Shaddow').style.display = 'none';", 400);
        window.setTimeout("$('fullPageOverlay_loading').innerHTML = '<br>Daten werden geladen!<br><br><img src=\""+imgDir+"loading_line.gif\" /><br /><br />';", 500);
    }
    else
    {
        $('fullPageOverlay_loading_shaddow').fade({duration: 0.15, from: 0.7, to: 0 });
        $('fullPageOverlay_loading').fade({duration: 0.2, from: 0.8, to: 0 });
        window.setTimeout("$('fullPageOverlay_loading_shaddow').style.display = 'none'; $('fullPageOverlay_loading').style.display = 'none'; $('fullPageOverlay').style.display = 'none';", 400);
    }
}

function viewLoginRemember()
{
    $('loginRemeberInfo').fade({duration: 0.3, from: 1, to: 0 });
    window.setTimeout("$('loginRemeberInfo').style.display = 'none';", 300);
    window.setTimeout("$('loginRemeberFields').setOpacity(0); $('loginRemeberFields').style.display = 'block'; $('loginRemeberFields').fade({duration: 0.5, from: 0, to: 1 });", 400);
}





function newProdukt(grpId)
{
    var add = {};
    add['grpId'] = grpId;
    viewOverlayTemplate('getTemplate', 'produkt_new', 'Neues Produkt erstellen', add, 500, 460, true);
}
function newGruppe(grpId)
{
    var add = {};
    add['grpId'] = grpId;
    viewOverlayTemplate('getTemplate', 'gruppe_new', 'Neue Gruppe erstellen', add, 600, 400, true);
}



function getContextEntrys(el, art)
{
    var def = new Array();
    var i   = 0;
    var gruppe = el.getAttribute('grpId');
    
    switch(art)
    {
        // -----------------------------------------------------------------
        case 'editGruppe':
            var grpId    = el.getAttribute('grpId');
            def[i] = new Object({'ANZEIGE': 'Neue Gruppe erstellen','ICON': 'icons/bullet_go.png','FUNCTION': 'newGruppe();'});
            i++;
            def[i] = new Object({'ANZEIGE': 'Neues Produkt erstellen','ICON': 'icons/bullet_go.png','FUNCTION': 'newProdukt(\''+grpId+'\');'});
            i++;
            def[i] = 'line';
            i++;
            def[i] = new Object({'ANZEIGE': 'Gruppe bearbeiten','ICON': 'icons/edit.png','FUNCTION': 'editGruppe(\''+grpId+'\');'});
            i++;
            def[i] = new Object({'ANZEIGE': 'Gruppe l&ouml;schen','ICON': 'icons/delete.png','FUNCTION': 'deleteGruppe(\''+grpId+'\');'});
            i++;
            break;

        // -----------------------------------------------------------------
        case 'editProdukt':
            var prdId    = el.getAttribute('prdId');

            def[i] = new Object({'ANZEIGE': 'Neue Gruppe erstellen','ICON': 'icons/bullet_go.png','FUNCTION': 'newGruppe();'});
            i++;
            def[i] = new Object({'ANZEIGE': 'Neues Produkt erstellen','ICON': 'icons/bullet_go.png','FUNCTION': 'newProdukt(\'\');'});
            i++;
            def[i] = 'line';
            i++;
            def[i] = new Object({'ANZEIGE': 'Produkt bearbeiten','ICON': 'icons/edit.png','FUNCTION': 'editProdukt(\''+prdId+'\');'});
            i++;
            def[i] = new Object({'ANZEIGE': 'Produkt l&ouml;schen','ICON': 'icons/delete.png','FUNCTION': 'deleteProdukt(\''+prdId+'\');'});
            i++;
            
            if(el.getAttribute('sichtbar') == "0")
            {
                def[i] = new Object({'ANZEIGE': 'Produkt in Karte anzeigen','ICON': 'icons/haken.png','FUNCTION': 'changeField(\'PRODUKTE\', \''+prdId+'\', \'ANZEIGEN\', \'1\');'});
                i++;
            }
            else
            {
                def[i] = new Object({'ANZEIGE': 'Produkt aus Karte ausblenden','ICON': 'icons/cross.png','FUNCTION': 'changeField(\'PRODUKTE\', \''+prdId+'\', \'ANZEIGEN\', \'0\');'});
                i++;
            }
            def[i] = 'line';
            i++;
            if(el.getAttribute('up') != 'false')
            {
                def[i] = new Object({'ANZEIGE': 'Nach oben','ICON': 'icons/arrow_up.png','FUNCTION': 'moveProdukt(\''+prdId+'\', \'up\', \''+gruppe+'\');'});
                i++;
            }

            if(el.getAttribute('down') != 'false')
            {
                def[i] = new Object({'ANZEIGE': 'Nach unten','ICON': 'icons/arrow_down.png','FUNCTION': 'moveProdukt(\''+prdId+'\', \'down\', \''+gruppe+'\');'});
                i++;
            }
            break;
    }

    return def;

}

function changeField(tab, id, feld, wert)
{
    add              = {};
    add['func']      = 'changeField';
    add['TAB']       = tab;
    add['ID']        = id;
    add['FELD']      = feld;
    add['WERT']      = wert;

    new Ajax.Request(preDir+'ajax.php', {
        method:     'post',
        parameters: add,
        onSuccess:  function(ret) {
            reloadSpeisekarte();
        }
    });
}


function moveToCenter(el)
{
    if(typeof(el) != 'object')
        el = $(el);

    var width       = 0;
    var height      = 0;

    // Fensterbreite
    if(isIE == true)
    {
        width       = (document.body.offsetWidth / 2)-(el.getWidth() / 2);
        height      = (document.body.offsetHeight / 2)-(el.getHeight() / 2);
    }
    else
    {
        width       = (innerWidth / 2)-(el.getWidth() / 2);
        height      = (innerHeight / 2)-(el.getHeight() / 2);
    }

    if(width < 0)
        width = 10;
    if(height < 0)
        height = 10;

    t = getScrollXY();
    height += t[1];
    el.style.top    = height+'px';
    el.style.left   = width+'px';
}

function editProdukt(prdId)
{
    var add = {};
    add['prdId'] = prdId;
    viewOverlayTemplate('getTemplate', 'produkt_edit', 'Produkt bearbeiten', add, 500, 460, true);
}
function saveProdukt()
{
    if($('ds_RECHNAME').value == '')
        $('ds_RECHNAME').value = $('ds_NAME').value;

    add                 = {};
    add['func']         = 'saveProdukt';
    add['ID']           = $('ds_ID').value;
    add['GRUPPEN_ID']   = $('ds_GRUPPEN_ID').value;
    add['NAME']         = $('ds_NAME').value;
    add['RECHNAME']     = $('ds_RECHNAME').value;
    add['PREIS_1']      = $('ds_euro_PREIS_1').value+'.'+$('ds_cent_PREIS_1').value;
    add['PREIS_2']      = $('ds_euro_PREIS_2').value+'.'+$('ds_cent_PREIS_2').value;
    add['BESCHREIBUNG'] = $('ds_BESCHREIBUNG').value;


    var tmp = $('zun_ZUSAETZE').getValue();
    add['ZUSAETZE'] = '';
    for(i in tmp)
    {
        if(typeof(tmp[i]) == 'string')
            add['ZUSAETZE'] += ','+tmp[i];
    }

    if($('ds_GANZTAG').checked)
        add['GANZTAG']  = 1;
    else
        add['GANZTAG']  = 0;

    if($('ds_ANZEIGEN').checked)
        add['ANZEIGEN']  = 1;
    else
        add['ANZEIGEN']  = 0;
        

    new Ajax.Request(preDir+'ajax.php', {
        method:     'post',
        parameters: add,
        onSuccess:  function(ret) {
            if(ret.responseText == 'OK')
            {
                hidePageOverlay();
                reloadSpeisekarte(add['GRUPPEN_ID']);
//                 alert('Produkt wurde gespeichert');
            }
            else
            {
                alert('Produkt konnte nicht gespeichert werden.');
            }
        }
    });
}

function moveProdukt(id, direction, gruppe)
{
console.log(gruppe);
    add = {};
    add['direction']    = direction;
    add['id']           = id;
    add['func']         = 'moveProdukt';
    add['gruppe']       = gruppe;

    new Ajax.Request(preDir+'ajax.php', {
        method:     'post',
        parameters: add,
        onSuccess:  function(ret) {
            if(ret.responseText == 'OK')
            {
                hidePageOverlay();
                reloadSpeisekarte(add['gruppe']);
//                 alert('Produkt wurde gespeichert');
            }
            else
            {
                alert('Produkt konnte nicht verschoben werden.');
            }
        }
    });
}

function reloadSpeisekarte(gruppe)
{
    if(gruppe == undefined)
        gruppe = '';
        
    add                 = {};
    add['func']         = 'getTemplate';
    add['tpl']          = 'speisekarte';
    add['gruppe']       = gruppe;
    
    new Ajax.Request(preDir+'ajax.php', {
        method:     'post',
        parameters: add,
        onSuccess:  function(ret) {
            $('content').innerHTML = ret.responseText;
        }
    });
}


function prdSelect(rahmen, grpId, prdId)
{
    add                 = {};
    add['func']         = 'getProduktSelect';
    add['grpId']        = grpId;
    add['prdId']        = prdId;
    add['rahmen']       = rahmen;

    $(rahmen).innerHTML = 'Produkte werden geladen...';

    new Ajax.Request(preDir+'ajax.php', {
        method:     'post',
        parameters: add,
        onSuccess:  function(ret) {
            $(rahmen).innerHTML = ret.responseText;
        }
    });
}