JSON = 'json';

var L={isUndefined:function(a){return typeof a==="undefined"},isNumber:function(a){},isString:function(a){return typeof a==="string"},isObject:function(a){return(a&&(typeof a==="object"||$.isFunction(a)))},trim:function(a){try{return a.replace(/^\s+|\s+$/g,"")}catch(b){return a}}};
var G = {
    /**
     *
     */
    init:function(config){
        G.config = config;
        G.uid = 0;
        this.menu("mainMenu");
        this.menu("adminMenu");
        G.initLO();
    },
    initLO : function(){
        G.bindLinks();
        G.initSideBoxes();
        G.bindAutoGrow();
        G.initTabs();
        G.helpText.bind();
        $(".highlight-mouse-over").mouseover(function(){
            $(this).addClass('ui-state-highlight');
        }).mouseout(function(){
            $(this).removeClass('ui-state-highlight');
        });
        $('.tr2, .tr3').mouseover(function(){
            $(this).addClass('trHighlight');
        }).mouseout(function(){
            $(this).removeClass('trHighlight');
        });
        $('.openid').click(function(){G.window("/user/openid-login/provider/" + $(this).attr('id'), '', 700);});
        $('.fbconnect').click(function(){G.window("/user/fbc-login", "Facebook Connect", 1000);});
    },
    /**
     *
     */
    time:function(){
        var d = new Date();
        return d.getTime();
    },
    /**
     *
     */
    initTabs : function(){
        var tabs = $('.jTabs');

        if(tabs.length == 0){
            return;
        }

        tabs.tabs({
            load: function(event, ui){
                G.initLO();
            }
        }).each(function(){
            $(this).removeClass('jTabs');
        });

    },
    initSideBoxes : function(){
        $('.sideBoxTrigger').click( function() {
            THIS = $(this);
            if ( THIS.hasClass('activeBoxTitle') ) {
                THIS.next('.content').addClass('hidden');
                THIS.parent().find('.bottom').addClass('hidden');
                THIS.removeClass('active');
                THIS.addClass('inactiveBoxTitle');
                THIS.removeClass('activeBoxTitle');
            }
            else{
                THIS.next('.content').removeClass('hidden');
                THIS.parent().find('.bottom').removeClass('hidden');
                THIS.addClass('activeBoxTitle');
                THIS.addClass('active');
                THIS.removeClass('inactiveBoxTitle');
            };
            return false;
        });
        $('.sideBoxTrigger').removeClass('sideBoxTrigger');
    },
    /**
     *
     */
    beutifyButtons:function(){
        $("button, input[type=submit]").each(function(){
            var btn = $(this);
            btn.addClass("ui-corner-all").hover(function(){
                btn.addClass("ui-state-hover");
            }, function(){
                btn.removeClass("ui-state-hover");
            });
        });

    },
    mouseoverActions : function(){
        $('.tr2').mouseover(function(){
            $(this).addClass('trHighlight');
        }).mouseout(function(){
            $(this).removeClass('trHighlight').addClass('tr2');
        });
        $('.tr3').mouseover(function(){
            $(this).addClass('trHighlight');
        }).mouseout(function(){
            $(this).removeClass('trHighlight').addClass('tr3');
        });
    },
    /**
     *
     */
    scrollTop : function(sel){
        $(sel).animate({scrollTop:0}, 'slow');
    },
    /**
     *
     */
    scrollBottom : function(sel){
        $(sel).animate({scrollTop:$(sel).attr("scrollHeight")}, 'slow');
    },
    /**
     *
     */
    labelInInput : function(inputElId, label){
        var el = $('#'+inputElId);
        if(  el.length == 0 ){
            return;
        }
        if( el.val().length == 0 ){
            el.val(label);
        }
        el.focus(function(){
            if( L.trim(el.val()) == label ){
                el.val('');
                el.removeClass('grayInput');
            }
        }).blur(function(){
            if( L.trim(el.val()).length == 0 ){
                el.val(label);
                el.addClass('grayInput');
            }
        });
        if( L.trim(el.val()) == label ){
            el.addClass('grayInput');
        }
    },
    /**
     *
     */
    helpText : {
        create : function(p1, p2){
            var elId;
            var hlpId;
            if( L.isUndefined(p2) ){
                hlpId = p1;
                elId = null;
            }
            else{
                hlpId = p2;
                elId = p1;
            }
            var html = '<button class="actBtn helpText" id="' + hlpId + '" style="background-color: #f6e19b !important;padding: 0 3px 1px 3px !important; border-color:#CEA21C !important;"><span class="ui-icon ui-icon-help"></span></button>';
            if( elId == null ){
                document.write(html);
            }
            else{
                $('#'+elId).html($('#'+elId).html()+html);

            }

        },
        bind : function(){
            $('.helpText').each(function(){
                var id = L.trim($(this).attr('id'));
                if( id.length > 0 ){
                    $(this).qtip({
                        content: {url : '/helptext/get/id/'+id},
                        show: 'mouseover',
                        hide: 'mouseout',
                        style: {name: 'cream', tip: true}
                    });
                }
                $(this).removeClass('helpText');
            });

        }
    },

    /**
     * G.postForm('formId');
     * 
     * G.postForm('formId', {
     *      hideStatus : true,
     *      showSuccessMsg: false,
     *      statusAfter: true,
     *      noSubmitLabel: true,
     *      onSuccess : function(res){
     *          ......
     *      },
     *      beforeSubmit: function(){
     *          ......
     *      },
     *      validate: function(fields){
     *      	......
     *      },
     *      onFailure: function(res){
     *          ......$('#meinDiv').addClass('error').html(res.error);
     *      }
     * });
     */
    postForm : function(formId, settings){

        var form = $("#"+formId);

        if( L.isUndefined(settings) ){
            settings = {};
        }

        var submitBtn = form.find("input[type=submit]");
        if( !L.isUndefined(settings.statusWrapId) ){
        	var status = $('#'+settings.statusWrapId);
        }
        else{
        	var status = $('<div class="postFormStatus mrT10" />')
        	if( L.isUndefined(settings.statusAfter) || settings.statusAfter == false ){
	            status.insertBefore(submitBtn);
	        }
	        else{
	            status.insertAfter(submitBtn);
	        }
        }
        
	        
        if(  L.isUndefined(settings.noSubmitLabel) ){
            $('<label />').insertBefore(submitBtn);
        }
        if( L.isUndefined(settings.successMsg) ){
            settings.successMsg = lang["changesSaved"];
        }
        if( !L.isUndefined(settings.hideStatus) ){
            settings.successMsg = false;
        }
        form.submit(function(e){
            e.preventDefault();
            if( !L.isUndefined(settings) && $.isFunction(settings.validate) && !settings.validate() ){
                return;
            }
            if( settings.hideStatus ){
            	status.addClass("hidden");
            }
            
            if( !L.isUndefined(settings) &&  $.isFunction(settings.beforeSubmit) ){
                settings.beforeSubmit();
            }

            var oldSubmitHtml = submitBtn.val();
            submitBtn.val(lang["pleaseWait"]);
            submitBtn.attr("disabled",true);
            $.post(form.attr('action'), form.serialize(), function(response){
                submitBtn.val(oldSubmitHtml);
                submitBtn.attr("disabled",false);
                status.html("");
                if( G.isOk(response) ){
                    if( settings.showSuccessMsg == false ||  settings.hideStatus ){
                        status.addClass('hidden');
                    }
                    else{
                        status.removeClass("hidden").addClass("notice").removeClass("error").html(settings.successMsg);
                    }
                    if( !L.isUndefined(settings) && $.isFunction(settings.onSuccess) ){
                        settings.onSuccess(response, formId);
                    }
                }else{
                	status.removeClass("hidden").addClass("error").removeClass("notice").html(response.error);
                    if( !L.isUndefined(settings) && $.isFunction(settings.onFailure) ){
                        settings.onFailure(response, formId);
                    }
                }
            }, "json");
        });
    },
    /**
     *
     */
    guid:function(){
        if( typeof G.uid == 'undefined'){
            G.uid = 0;
        }
        return "GUID" + (++G.uid);
    },
    /**
     *
     */
    url:function(){
        var url=G.config.baseUrl;
        for(var i=0;i<arguments.length;i++){
            if(L.isUndefined(arguments[i])){
                continue;
            }
            if(i>0){
                url+='/';
            }
            arguments[i].toString().replace("/","_");
            url+=arguments[i];
        }
        return encodeURI(url);
    },

    /**
     *
     */
    image:function(img, className, buildLink){

        buildLink = ( L.isUndefined(buildLink) ) ? true : buildLink;
        var link = G.config.imagesDir + img;
        if( !buildLink ){
            return link;
        }
        className = ( L.isUndefined(className) ) ? 'img' : className;
        return '<img src="' + link + '" class="' + className + '" />';
    },
    /**
     * checks if result of JSON response indicates success
     */
    isOk : function(response){
        
        if( !L.isObject(response) && L.isString(response) ){
            try{
                response =  eval('(' + response + ')');
            }
            catch(e){
                return false;
            }
        }
        if( G.config.isLogged && parseInt(response.auth) == 0 ){
            response.error = lang["sessTimeout"];
            G.OL.open('/user/login-required-ajax/', 'Login');
            return false;
        }
        return ( parseInt(response.isOk) == 1 );
    },
    /**
     *
     */
    error:function(wrap, e ){
        $("#"+wrap).removeClass("notice").addClass("error").removeClass("hidden").html(e);
    },
    /**
     *
     */
    notice:function(wrap, n ){
        $("#"+wrap).removeClass("error").addClass("notice").removeClass("hidden").html(n).show();
    },
    /**
     * deletes something, and removes it's containing div
     */
    deleteIt : function( url, pars, wrapId, confirmation, onSuccess){
        G.confirm(confirmation, lang["confirm"], function(){
            $.post(url,pars,function(response){
                if( G.isOk(response) ){
                    if( $.isFunction(onSuccess) ){
                        onSuccess(response);
                        return;
                    }
                    $("#"+wrapId).fadeOut("slow",function(){
                        $(this).remove();
                    });
                }else if( response.error.length > 1 ){
                    G.alert(response.error);
                }
            }, "json");
        });
    },
    
    /**
     *
     */
    alert : function(msg,title, onClose){
        var aId = G.guid();
        var a = $('<div id='+aId+'><p class="fs7">' + msg + "</p></div>");
        bs = {};
        bs[lang["close"]] = function(){
            $(this).dialog('destroy');
            $("#"+aId).remove();
            if( $.isFunction(onClose) ){
                onClose();
            }
        };

        a.dialog({
            bgiframe: true,
            resizable: false,
            modal: true,
            dialogClass: 'alert',
            'title': title,
            buttons: bs,
            close: function(ev, ui){
                $("#"+aId).remove();
                if( $.isFunction(onClose) ){
                    onClose();
                }
            }
        });
    },

    /**
     *
     */
    confirm : function(question, title, onOk, onCancel){
        var a = $('<div><p class="fs7">' + question + "</p></div>");
        bs = {};
        bs[lang["yes"]] = function() {
            $(this).dialog('destroy');
            if( $.isFunction(onOk) ){
                onOk(true);
            }
        };
        bs[lang["cancel"]] = function() {
            $(this).dialog('destroy');
            if( $.isFunction(onCancel) ){
                onCancel(false);
            }
        };

        a.dialog({
            bgiframe: true,
            resizable: false,
            modal: true,
            dialogClass: 'alert',
            'title': title,
            buttons: bs

        });
    },

    /**
     * @desc reloads current page
     */
    reloadWindow : function(){
        href=window.location.href;
        if( href.charAt(href.length-1) == '#' ){
            href = href.substr(0, href.length-1);
        }
        window.location.href = href;
    },

    /**
     * @desc redirects user to 'href'
     */
    goTo  :function(href){
        window.location.href = href;
    },

    /**
     * @desc shows an element
     * @param sel: the jquery selector of the element
     * @param text(optional): the text to show in the element
     */
    show : function(sel, text){
        var el = $(sel);
        if( !L.isUndefined(el) ){//if el exists
            if( !L.isUndefined(text) ){//if text is set
                el.text(text);//set el text
            }
            el.removeClass("hidden");//show el
        }
    },

    /**
     * @desc hides an element
     * @param sel: the jquery selector of the element
     * @param clear: wheather to clear the contents of the element or not
     */
    hide : function(sel, clear){
        var el = $(sel);
        if( !L.isUndefined(el) ){
            el.addClass("hidden");
            if(clear==true){
                el.text("");
            }
        }
    },

    /**
     * @desc either hides or show an element
     * @param sel: jquery selector of the element to operate on
     */
    toggle : function(sel, link, showLabel, hideLabel){

        var el = $(sel);
        if( L.isUndefined(el) ){
            return;
        }
        if( !el.hasClass("hidden") ){
            el.addClass("hidden");
            if( !L.isUndefined(showLabel) ){
                $(link).html(showLabel);
            }
        }else{
            el.removeClass("hidden");
            if( !L.isUndefined(hideLabel) ){
                $(link).html(hideLabel);
            }
        }
    },

    toggleClasses : function(el, cls1, cls2){
        if( el.hasClass(cls1) ){
            el.removeClass(cls1).addClass(cls2);
            return;
        }
        el.removeClass(cls2).addClass(cls1);
    },

    /**
     * @desc sets a cookie
     * @param n: name of the cookie
     * @param v: value of the cookie
     */
    cookie : function(n, v, expires){
        if( L.isUndefined(v) ){
            return $.cookie(n);
        }
        if( L.isUndefined(expires) ){
            expires = 0;
        }
        $.cookie(n,v,{'expires': expires, 'path': '/'});
    },

    /**
     * @desc fades out an element and removes it from DOM
     * @param sel: jquery selector of the element
     */
    fadeOut : function(sel){
        $(sel).fadeOut("slow",function(){
            $(this).remove();
        });
    },
    /**
     * @desc gets the extention of a file
     * @param fileName
     */
    getFileExtention:function(fileName){
        if( fileName.length < 2 ){
            return '';
        }
        var dotPos = fileName.lastIndexOf(".");
        if( dotPos==-1 ){
            return '';
        }
        if( dotPos == fileName.length-1 ){
            return '';
        }
        return fileName.substr(dotPos+1, fileName.length).toLowerCase();
    },

    /**
     * @desc checks wheather a file is an image file or not
     * @param fileName
     */
    isImageFile : function(fileName){
        var ext = G.getFileExtention(fileName);
        return ( ext == 'jpg' || ext == 'jpeg' || ext == 'gif' || ext == 'png' );
    },

    /**
     * @desc ajaxify links, so that links wich have a class 'ajax' gets loaded by ajax in the container set in 'rev'
     *       <a href="target.php" class="ajax" rev="wrap"></a> when clicked, target.php gets loaded by ajax, the output is put in
     *       the div or span with the ID 'wrap'
     *
     */
    bindLinks : function(){
        $('a.ajax').click(function(e){
                e.preventDefault();
                var link = $(this);
                var targetSel = "#"+link.attr("rev");
                G.load(link.attr('href'), targetSel);
                
        });
        $('a.ajax').removeClass('ajax');

         $('.ui-icon-circle-arrow-s').each(function(){
                var THIS = $(this);
                THIS.parent().click(function(){
                    if( THIS.hasClass('ui-icon-circle-arrow-s') ){
                        THIS.removeClass('ui-icon-circle-arrow-s').addClass('ui-icon-circle-arrow-n');
                    }else{
                        THIS.removeClass('ui-icon-circle-arrow-n').addClass('ui-icon-circle-arrow-s');
                    }
                });
            });

    },
    /**
     * @desc execute inline javascript that is loaded by ajax
     * @param el: element Id to look inside for scripts
     */
    inlineScripts:function(el){
        if( typeof el == "string" ){
            el = $("#"+el);
        }

        el.children("script").each(function(e){

            // try{
                 eval(this.text);
             // }
             // catch(e){
             // }
        });
    },
    /**
     * @desc apply autogrow plugin to any textarea with a class name 'autogrow'
     */
    bindAutoGrow:function(){
        if( $('textarea.autogrow').length == 0 ){
            return;
        }
        $('textarea.autogrow').autogrow({
            maxHeight: 500,
            lineHeight: 16
        });
        $('textarea.autogrow').removeClass('autogrow');
    },
    /**
     * @desc loads a page into a div by ajax
     * @param href: the page to load
     * @param targetSel: jquery selector of the target(where to show the loaded page)
     * @showStatus: if true, an image indicating loading will be shown in the target while loading the page
     */
    load : function(href, targetSel, showStatus, onSuccess){
        var target = $(targetSel);
        if(!L.isUndefined(showStatus) && showStatus==true ){
            target.html(G.image('loading1.gif'));
        }
        $.get(href, function(data){
            try{
                response =  eval('(' + data + ')');
                if( parseInt(response.isAuthError) == 1 ){
                    G.OL.open('/user/login-required-ajax', 'Login');
                    return;
                }
            }
            catch(e){
                
            }
            target.html(data);
            G.initLO();

            G.inlineScripts(target);
            if( $.isFunction(onSuccess) ){
                 onSuccess();
            }
        });
    },
    /**
     * @desc overlay
     */
    OL:{
        /**
         *
         */
        container:null,
        /**
         * open url and shows it in a overlay
         *
         * @param url: url of the page to be loaded in the overlay
         * @param pTitle: title of the overlay
         * @param pWidth: width of the overlay
         *
         */
        open:function(url, pTitle, pWidth, pMinHeight){
            var id = G.guid();//generate a unique id
            if( L.isUndefined(pTitle) ){
                pTitle = '';
            }

            if( L.isUndefined(pWidth) ){
                pWidth = 600;
            }

            this.container = $('<div id="'+id+'"></div>');//creates a container div



            this.container.dialog({//creates the overlay
                bgiframe: true,
                autoOpen: true,
                modal: true,
                width: pWidth,
                minHeight: pMinHeight,
                draggable:true,
                resizable: true,
                position: ['center',50],

                title : pTitle,
                close: function() {
                    $(this).dialog('destroy');
                    $("#"+id).remove();
                }
            });

            G.load(url, $("#"+id+''), true);//load the page into the container
        },
        /**
         * closes the overlay
         */
        close:function(){
            this.container.dialog('close');

        }
    }
};
/**
 * @desc setup menu
 * @id id of the menu to setup
 */
G.menu = function(id){
    var transition = {overtime:300, outtime:300};//transition time
    var menu = $("#"+id);
    if( menu.length == 0 ){//id is invalid
        return;
    }
    var active=null;//the active submenu
    var headers = menu.children("li");//top level LI's
    headers.hover(function(e){//mouse over
        var item = $(this);
        item.addClass('selected');
        if( item.hasClass("ui-corner-left") ){
            item.removeClass("ui-corner-left").addClass("ui-corner-left-inactive");
        }
    },function(e){//mouse out
        var item = $(this);
        item.removeClass('selected');
        if( item.hasClass("ui-corner-left-inactive") ){
            item.removeClass("ui-corner-left-inactive").addClass("ui-corner-left");
        }
    });

    headers.each(function(i){
        var top = $(this);
        top.attr("id", "m"+G.guid());
        if(  top.children("ul").length == 0 ){
            return;// top level LI doesn't have a sub menu
        }
        //to level LI has a sub menu

        top.css({zIndex: 1000-i});
        top.hover(function(e){//mouse over
            var el = $(this);
            var ul = el.children("ul");//get submenu
            function show(){
                if( active!= null && active != el.attr("id") ){//if another submenu is still visible, then do nothing
                    return;
                }
                ul.fadeIn('fast');
                active = el.attr("id");
            }
            setTimeout(show, 1);//show submenu

        },
        function(e){//mous out
            var el = $(this);
            var oTarget = $(e.relatedTarget);//target of the mouse move
            function hide(){
                var p = el.parent().parent();
                if( el.attr("id") == oTarget.attr("id") ){//if mouse is still over the same LI then do nothing
                    return
                }
                el.children("ul").fadeOut("fast");
                active  = null;
            };
            setTimeout(hide, 0);
        });
    });
    menu.find("ul").css({display:'none', visibility:'visible'});//hide all submenus

};
/**
 * @desc highlights one element on the page..
 * @param elId the element to highlight
 */
G.toggleHighlight = function(elId){
    if( !L.isUndefined(G.highlightOldEl) ){//if another element is already highlighted, then de-highlight it
        $('#'+G.highlightOldEl).removeClass('ui-state-highlight');
    }
    $('#'+elId).addClass('pd10 cf ui-widget ui-widget-content ui-corner-all ui-state-highlight');//highlight the element
    G.highlightOldEl = elId;//keep track
};
/**
 * @desc reloads captcha image
 * @param imgId : ID of the image element
 * @param inputId : ID of the related input element
 */
G.reloadCaptcha = function(imgId, inputId){
    $("#"+imgId).attr("src", '/default/user/captcha/'+Math.random());
    $('#'+inputId).val('');
};
/**
 * 
 */
G.gMap = {
    map : null,
    directions : null,
    init : function(mapId, directionsWrap){
        G.gMap.map = new GMap2(document.getElementById(mapId));
        G.gMap.map.setUIToDefault();
        G.gMap.map.setCenter(new GLatLng(50,10), 5);
        G.gMap.map.setMapType(G_NORMAL_MAP);
        G.gMap.map.checkResize();
        G.gMap.directions = new GDirections(G.gMap.map, document.getElementById(directionsWrap));
        G.gMap.allowedBounds = new GLatLngBounds(new GLatLng(47.161334,5.793456), new GLatLng(55.529874,14.143066));

        GEvent.addListener(G.gMap.map, "move", function(){
            G.gMap.checkBounds();
        });
    },
    checkBounds : function(){
        if (G.gMap.allowedBounds.contains(G.gMap.map.getCenter())) {
            return;
        }
        var C = G.gMap.map.getCenter();
        var X = C.lng();
        var Y = C.lat();

        var AmaxX = G.gMap.allowedBounds.getNorthEast().lng();
        var AmaxY = G.gMap.allowedBounds.getNorthEast().lat();
        var AminX = G.gMap.allowedBounds.getSouthWest().lng();
        var AminY = G.gMap.allowedBounds.getSouthWest().lat();

        if (X < AminX) {X = AminX;}
        if (X > AmaxX) {X = AmaxX;}
        if (Y < AminY) {Y = AminY;}
        if (Y > AmaxY) {Y = AmaxY;}

        G.gMap.map.setCenter(new GLatLng(Y,X));
    },
    setType : function(type){
        G.gMap.map.setMapType(type);
    },
    setCenter : function(latitude, longitude, zoom){
        G.gMap.map.setCenter(new GLatLng(latitude,longitude), zoom);
    },
    setSingleMarker : function(latitude, longitude, info){
        G.gMap.map.clearOverlays();
        G.gMap.addMarker(latitude, longitude, info);
    },
    addMarker:function(latitude, longitude, info){
        var point = new GLatLng(latitude,longitude);
        var marker = new GMarker(point);
        G.gMap.map.addOverlay(marker);
        if( !L.isUndefined(info) ){
            marker.openInfoWindowHtml(info);
        }
        G.gMap.map.checkResize();
    },
    showAddress : function(address, info){
        var geocoder = new GClientGeocoder();
        geocoder.getLatLng(address, function(point) {
            if( point ){
                G.gMap.setCenter(point.lat(), point.lng(), 14);
                G.gMap.setSingleMarker(point.lat(), point.lng(), info);
            }
        });

    },
    get : function(){
        return G.gMap.map;
    },
    locator : {
            currentPosition : null,
            onChange : null,
            init : function(onChange){
                G.gMap.locator.onChange = onChange;
                GEvent.addListener(G.gMap.map, "click", G.gMap.locator.getLoc);
                G.gMap.locator.geocoder = new GClientGeocoder();
            },
            getLoc : function(overlay, latlng){
                if (latlng != null) {
                    address = latlng;
                    G.gMap.locator.geocoder.getLocations(latlng, G.gMap.locator.markLocation);
                  }
            },
            markLocation : function(response){
                G.gMap.map.clearOverlays();
                if (!response || response.Status.code != 200) {
                    alert("Fehler");
                }
                else{
                    G.gMap.locator.currentPosition = response.name.split(',');
                    G.gMap.setSingleMarker(G.gMap.locator.currentPosition[0], G.gMap.locator.currentPosition[1]);
                    if( $.isFunction(G.gMap.locator.onChange) ){
                        G.gMap.locator.onChange(G.gMap.locator.currentPosition);
                    }
                }
            },
            getCoordinates : function(){
                return G.gMap.locator.currentPosition;
            }
    },
    showDirections : function(from, to){
        G.gMap.directions.load("from: " + from + " to: " + to, {locale:"de_DE"});
    }
};
/**
 * @desc betriebs related actions
 */
G.betriebs = {
    favs : {
        /**
         * @desc adds or removes a restaurant to Favorites
         * @param betriebId : ID of the betrieb to act on
         * @param {bool} addOrRemove: true => add, false => remove
         * @param btn: the button which invoked the method
         */
        addRemove : function(betriebId, addOrRemove,btn){
            addOrRemove = addOrRemove ? 'add' : 'remove';

            $.post('/betrieb/add-to-favs/id/'+betriebId,{'addOrRemove':addOrRemove},function(res){
                if( G.isOk(res) ){
                    G.reloadWindow();
                }
            },'json');
        }
    }
};
/**
 * @desc search related actions
 */
G.search = {
        /**
         * @desc initializes, setup search form
         * @param queryObj: object containing search data
         *             {
         *                 isZip : bool, //wheather we are searching using zip code or location
         *                 value: zipcode, // exists only if we are searching using zip code
         *                 id: locationId //exists only if we are searching using location
         *                 }
         */
        init : function(locationEl, whatEl, labelIt){
            if( !L.isUndefined(labelIt) && labelIt ){
                G.labelInInput(locationEl, 'PLZ oder Ort');
            }

            $('#' + locationEl).autocomplete('/geoac/zip-or-location/', {//zip and location autocomplete
                multiple: false,
                dataType: "json",
                matchCase: false,
                autoFill: true,
                max:20,
                parse: function(data) {
                    return $.map(data, function(row) {
                        if( row.isZip == 'true' ){
                            return {
                                data: row,
                                value: row.value,
                                result: row.value
                            };
                        }else{
                            return {
                                data: row,
                                value: row.value,
                                result: row.value
                            };
                        }
                    });
                },
                formatItem: function(item) {
                    if( item.isZip == 'true' ){
                        return item.value + ", " + item.location;
                    }else{
                        return item.value + ", " + item.state;
                    }
                }
            }).result(function(e, item) {//on result selection,,, sets the queryObject to the new selected zip or location


        });

        if( !L.isUndefined(whatEl) ){
            if( !L.isUndefined(labelIt) && labelIt ){
                G.labelInInput(whatEl, 'z.B. Italienisch');
            }
            $('#' + whatEl).autocomplete('/search/was-ac/', {//infos, options auto complete
                multiple: false,
                dataType: "json",
                matchCase: false,
                autoFill: true,
                max:50,
                parse: function(data) {
                    return $.map(data, function(row) {
                        return {
                                data: row,
                                value: row,
                                result: row
                            };
                    });
                },
                formatItem: function(item) {
                        return item;
                }
            });
        }

    }
};
/**
 * 
 */
G.galerie = {
    init : function(betriebId){
        G.load('/betrieb-edit/galerie/sub/photoList/id/'+betriebId, '#photoListWrap');
        $("#uploadGPhotoForm").jup({
            "validate" : function(fields){
                if( fields.userfile.length == 0 ){
                    G.error('uploadGPhotoStatus', lang['photoFileNotSelected']);
                    return false;
                }
                if( !G.isImageFile(fields.userfile) ){
                    G.error('uploadGPhotoStatus', lang['photoExtNotice']);
                    return false;
                }
                $('#uploadGPhotoStatus').removeClass('error').html('');

                return true;
            },
            "beforeUpload":function(){
                G.notice('uploadGPhotoStatus', lang["photoUploading"] + G.image("loading1.gif"));
            },
            "onComplete":function(response, error){
                // submitBtn.attr("disabled",false);
                if( G.isOk(response) ){
                    G.notice('uploadGPhotoStatus', lang["success"]);
                    var newFile = $('<input type="file" name="userfile" />');
                    newFile.insertAfter('#elUserfile');
                    $('#elUserfile').remove();
                    newFile.attr('id','elUserfile');
                    $('#elTitle').val('');
                    $('#elDescription').val('');
                    G.load('/betrieb-edit/galerie/sub/photoList/id/'+betriebId, '#photoListWrap');
                    // uStatus.addClass("notice").removeClass("error").html(lang["success"]);
                }else if( response.error.length > 0 ){
                    G.error('uploadGPhotoStatus', response.error);
                    // uStatus.addClass("error").removeClass("notice").html(response.error);
                }else{
                    G.error('uploadGPhotoStatus', lang['unkownError']);
                }
            }
        });
    },
    deletePhoto : function(betriebId, photoId){
        $.post('/betrieb-edit/galerie/id/'+betriebId+'/sub/deletePhoto/',{'photoId':photoId}, function(res){
            if( G.isOk(res) ){
                G.fadeOut('#photo'+photoId);
            }
        },'json');
    }
};
/**
 * 
 */
G.gutschein = {
    init : function(){
        $('#createGutscheinForm').submit(function(e){
            e.preventDefault();
        });

        $("#elValidUntil").datepicker({dateFormat: 'dd.mm.yy'})
        .datepicker('option', 'dateFormat', 'yy-mm-dd')
        .datepicker('option', 'minDate', '+1')
        .datepicker('option', 'maxDate', '+4y')
        .datepicker('option', 'changeMonth', true)
        .datepicker('option', 'changeYear', true);
    },
    setLayout : function(layout){
        $('#selectedLayoutPreview').attr('src', G.image('gutscheine/'+layout+'.jpg', null, false));
        $('#elLayout').val(layout);
    },
    validate : function(){
        if( $('#elLayout').val() == '' ){
            G.alert('Bitte wählen sie ein Layout für Ihren Gutschein aus.','Fehler');
            return false;
        }
        return true;
    },
    preview : function(betriebId, btn){
        if( !G.gutschein.validate() ){
            return false;
        }
        btn = $(btn);
        var btnOVal = btn.html();
        btn.attr('disabled', true);
        btn.html('Bitte warten...');
        $.post('/betrieb-edit/create-gutschein/sub/preview/id/'+betriebId, $('#createGutscheinForm').serialize(), function(res){
            btn.attr('disabled', false);
            btn.html(btnOVal);
            if( G.isOk(res) ){
                G.alert('<a href="'+res.pdfLink+'">link</a>', 'Preview');
            }else{
                G.alert(res.error, 'Fehler');
            }
        },'json');
    },
    create : function(betriebId, btn){
        if( !G.gutschein.validate() ){
            return false;
        }
        btn = $(btn);
        var btnOVal = btn.html();
        btn.html('Bitte warten...');
        btn.attr('disabled', true);
        $.post('/betrieb-edit/create-gutschein/sub/create/id/'+betriebId, $('#createGutscheinForm').serialize(), function(res){
            if( G.isOk(res) ){
                G.goTo('/betrieb-edit/gutschein/id/'+betriebId);
            }else{
                G.alert(res.error, 'Fehler');
            }
            btn.attr('disabled', false);
            btn.html(btnOVal);
        },'json');
    },
    deleteIt : function(betriebId, gutscheinId, elLink){
        G.confirm('Sicher?',lang["confirm"], function(){
            elLink = $(elLink);
            var elLinkOVal = elLink.html();
            elLink.html('<img src="/imgs/icon_load.gif" style="margin-top:10px" />');
            $.post('/betrieb-edit/delete-gutschein/id/'+betriebId, {'gutscheinId':gutscheinId}, function(res){
                if( G.isOk(res) ){
                    G.fadeOut('#gutschein'+gutscheinId);
                }else{
                    G.alert(res.error, 'Fehler');
                    elLink.html(elLinkOVal);
                }
            },'json');
        });
    }
};
/**
 * 
 */
G.locZipCodeAutoComplete = function(elZipCodeId, elLocationId, limit){
    if( L.isUndefined(limit) ){
        limit = 20;
    }
    $("#"+elZipCodeId).autocomplete('/geoac/zip/', {
        multiple: false,
        dataType: "json",
        matchCase: false,
        autoFill: true,
        max:limit,
        width:250,
        parse: function(data) {
            return $.map(data, function(row) {
                    return {
                        data: row,
                        value: row.zipCode,
                        result: row.zipCode
                    };
            });
        },
        formatItem: function(item) {
            return item.zipCode + " " + item.location;
        }
    }).result(function(e, item) {
        $("#"+elLocationId).val(item.location);
    });
    /*$("#"+elLocationId).autocomplete('/geoac/location/', {
        multiple: false,
        dataType: "json",
        matchCase: false,
        autoFill: true,
        max:100,
        width:250,
        parse: function(data) {
            return $.map(data, function(row) {
                    return {
                        data: row,
                        value: row.name,
                        result: row.name
                    };
            });
        },
        formatItem: function(item) {
            return item.name + ", " + item.state ;
        }
    });*/
    $("#"+elLocationId).attr('readonly', 'readonly');
};

G.mailbox = {
        checkAll : function(check){
            $(".msgCheck").each(function(){
                $(this).attr("checked",check);
            });
        },
        deleteSelected : function(){
            var selected = [];
            $(".msgCheck").each(function(){
                if( $(this).attr("checked") ){
                    selected.push($(this).attr('id'));
                }
            });
            if( selected.length > 0 ){
                $.post('/mailbox/delete', {'ids':selected.join(';')}, function(res){
                    if( G.isOk(res) ){
                        G.reloadWindow();
                    }
                }, "json");
            }
        }
};

G.window = function(url, title, width, height){
    if( L.isUndefined(title) ){
        title = "";
    }
    if( L.isUndefined(width) ){
        width=500;
    }
    if( L.isUndefined(height) ){
        height=500;
    }
    open(url,title, "toolbar=no,menubar=no,width="+width+",height="+height+",resizable=yes,scrollbars=yes")
};

G.welcome = {
    cookieName : 'wlcmHide',
    cookieValue : 'y',
    wrap : null,
    init : function(){
        if( G.cookie(G.welcome.cookieName) == G.welcome.cookieValue ){
            return;
        }
        G.welcome.show();
    },
    closeIt : function(goTo){
        G.welcome.disable();
        if( G.welcome.wrap ){
            $('#wlcmOL').remove();
            G.welcome.wrap.remove();
            G.welcome.wrap = null;
        }
        if( !L.isUndefined(goTo) ){
            G.goTo(goTo);
        }
    },
    show : function(){
        $('<div id="wlcmOL" class="ui-widget-overlay" style="z-index:10000">').css('height',$(document).height()).insertBefore('#allWrap');
        G.welcome.wrap = $('<div id="wlcmWrap" class="absolute pd5" style="width:845px;height:600px;z-index:1000001;" />');
        G.welcome.wrap.appendTo('#allWrap');
                
        $.get('/index/welcome', {}, function(res){
            G.welcome.wrap.html(res);
                        absCenter(G.welcome.wrap);
        });
    },
    disable : function(){
        expires = new Date();
        expires.setDate(expires.getDate()+15);
        G.cookie(G.welcome.cookieName, G.welcome.cookieValue, 30);
    }
};

function absCenter(el, dWidthSub, dHeightSub) {
    if( L.isUndefined(dWidthSub) ){
        dWidthSub = 0;
    }
    if( L.isUndefined(dHeightSub) ){
        dHeightSub = 0;
    }
    el.css("position","absolute");
    var top = ($(window).height() - el.height()) / 2 + $(window).scrollTop() - dHeightSub;
    if( top < 0 ){
        top = 0;
    }
    left = ($(window).width() - el.width() ) / 2 + $(window).scrollLeft() - dWidthSub;
    if( left < 0 ){
        left = 0;
    }
    el.css("top", ( top + "px"));
    el.css("left", ( left + "px"));
    return this;
}


$(document).ready(function(){
    var lHeight = 0;
    var rHeight = 0;
    var tlEls = [];
    $('.tlEntry').each(function(){
        tlEls.push( $(this) );
    });
    setTimeout(function(){
        for(var i=0; i < tlEls.length; i++){
            
            var isLeft = tlEls[i].hasClass('tlLeft');
            var isFixed = tlEls[i].hasClass('fix');
            if( isFixed ){
                if( isLeft ){
                    lHeight += tlEls[i].outerHeight()+20;
                }
                else{
                    rHeight += tlEls[i].outerHeight()+20;
                }
                continue;
            }
            if( lHeight > rHeight ){
                tlEls[i].removeClass('tlLeft');
                tlEls[i].addClass('tlRight');
                rHeight += tlEls[i].outerHeight()+20;
            }
            else{
                tlEls[i].removeClass('tlRight');
                tlEls[i].addClass('tlLeft');
                lHeight += tlEls[i].outerHeight()+20;
            }
            continue;
        }
    }, 100);
});

function deleteComment(id, wrapId){
    $.post('/comments/delete-comment/', {'id':id}, function(res){
        $('#'+wrapId).remove();
    });
    
}
