var level = 'unknown';
var mapsNeedsUpdate = true;

var globalErrObject;

var seconds = 1000;
var minutes = 60*seconds;
var hours = 60*minutes;


function assert(condition, message) {
    message = 'Assertion error: ' + message;
    var stacktrace = String(getStackTrace());
    var body = {
        stacktrace: stacktrace,
        message: message,
        url: document.location,
        line: ''
    };
    new Ajax.Request('/ajax/customer/javascriptexception/',
        {
            postBody: Object.toQueryString(body)
        }
    );
    write(message);
}

function write(a) {
    if (typeof console != 'undefined' && typeof console.log != 'undefined') {
        console.log(a);
    }
}

function google_analytics(name, value) 
{
    if (typeof _gaq != 'undefined' ) {
        if ((name == 'page') || (name == '')) {
            values = value.split('/');
            for (var i = values.length-1; i >= 0; i--) {
                if (values[i] != '') {
                    name = values[i];
                    break;
                }
            }
        }
        _gaq.push(['_trackEvent', name, value]);
    }
}

function analytics(value) 
{
    google_analytics('page', value);
}

Event.APPLE_KEY = 224;
Event.SHIFT_KEY = 16;
Event.OPTION_KEY = 18;
Event.CONTROL_KEY = 17;

function keycode_allowed(keyCode) {
    var ignore_keys = [
        Event.CONTROL_KEY,
        Event.SHIFT_KEY,
        Event.APPLE_KEY,
        Event.OPTION_KEY,
        Event.KEY_TAB
    ];
    if(keyCode) {
        return ignore_keys.indexOf(keyCode) == -1;      
    } else {
        return true;
    }
}

var GlobalUpdater = {
    linkHandlers: {   // allows us to dynamically override the link targets
                      'restaurant/': function() { return 'restaurant/'+controller.address.city_slug+'/';  }
                  },
    
    updateAjaxLink: function(element) {
        if(Element.hasClassName(element, 'hasEvent')) {
            return;
        }
        Element.addClassName(element, 'hasEvent');
        YAHOO.util.Event.addListener(element, "mouseover", GlobalUpdater.hoverSelect);
    },

    updateAjaxLinks: function() {
        var spans = YAHOO.util.Selector.query('span.select, .withaction');
        var len = spans.length;
        for(i = 0; i < len; i++) {
            var element = spans[i];
            GlobalUpdater.updateAjaxLink(element);
        }
    },

    hoverSelect: function(e) {
                    Element.addClassName(this, 'hover');
                    YAHOO.util.Event.addListener(YAHOO.util.Selector.query('ul, span.moar', this), "mouseout", GlobalUpdater.unhoverSelect);
                 },

    unhoverSelect: function(e) {
                    if(e.x <= 1 || e.y <= 1 || e.x >= Element.getWidth(this) || e.y >= Element.getHeight(this)) {
                        Element.removeClassName(this.parentNode, 'hover');
                    }
                 }
};

function Promise() {
    this.callback_queue = [];
    this.errback_queue = [];
    this.cObj = null;
    this.throbber_disabled = false;
    this.wasAborted = false;
    
    this.addCallback = function(fun, context) {
        this.callback_queue.push({fun: fun, context: context});
        this._process();
        return this;
    };

    this.fireCallback = function(result) {
        this.callback_result = result;
        this._process();
    };

    this.addErrback = function(fun, context) {
        this.errback_queue.push({fun: fun, context: context});
        this._process();
        return this;
    };
    
    this.fireErrback = function(result) {
        this.errback_result = result;
        this._process();
    };
    
    this._process = function() {
        if(this.wasAborted)
            return;
        
        var x = null;
        var fun = null;
        var context = null;
            
        if (this.callback_result) {
            for (x in this.callback_queue.reverse()) {
                if (! YAHOO.lang.hasOwnProperty(this.callback_queue, x) )
                    continue;
                fun = this.callback_queue[x].fun.curry(this.callback_result);
                context = this.callback_queue[x].context;
                fun.call(context);
            }
            this.callback_queue = [];
            if (!this.throbber_disabled) {
                Throbber.release();
            }
        }
        if ( this.errback_result ) {
            var status = this.errback_result.status;
            if((status >= 500 && status < 600) ) {
                /* when no errback is set, call default errback */
                if(!this.errback_queue.length)
                    this.defaultErrback(this.errback_result);
                
                for (x in this.errback_queue.reverse()) {
                    if (! YAHOO.lang.hasOwnProperty(this.errback_queue, x) )
                        continue;
                    fun = this.errback_queue[x].fun.curry(this.errback_result);
                    context = this.errback_queue[x].context;
                    fun.call(context);
                }
            }
            this.errback_queue = [];  
            if (!this.throbber_disabled) {
                Throbber.release();
            }
        }
    };
    
    this.abort = function() {
        if(this.wasAborted || !YAHOO.util.Connect.isCallInProgress(this.cObj))
            return;
            
        YAHOO.util.Connect.abort(this.cObj);
        if (!this.throbber_disabled) {
            Throbber.release();
        }
        this.wasAborted = true;
    };
    
    this.asyncRequest = function(method, url, callback, postBody) {
        this.cObj = YAHOO.util.Connect.asyncRequest(method, url, callback, postBody);
    };
    
    this.defaultErrback = function(err) {
        GrowlMessage(gettext('<b>Sorry, es ist ein Fehler aufgetreten.</b><br />Wir wurden informiert und kümmern uns darum! Bitte versuche, die Seite zu aktualisieren, um fortzufahren!'), 0);
        globalErrObject = err;
    };
}

function dict_update(a, b) {
    for(var key in b) {
        if(YAHOO.lang.hasOwnProperty(b, key))
            a[key] = b[key];
    }
    return a;
}

function callRemote(url, postBody, method, nothrobber) {
    if (!nothrobber) {
        Throbber.retain();
    }
    method = method || 'POST';

    if(!postBody)
        postBody = '';
    
    postBody += '&' +window.location.search.substring(1);

    if(method == 'GET' && postBody) {
        url += '?' + postBody;
    }
    
    /* needed for FF, because it doesn't send content-length otherwise */
    if(!postBody)
        postBody = ' ';
    
    var promise = new Promise();
    
    if (nothrobber) {
        promise.throbber_disabled = true;
    }

    var callback =  {
      success: function(o) { promise.fireCallback(o); },
      failure: function(o) { promise.fireErrback(o); }
    };
    
    promise.asyncRequest(method, url, callback, postBody);
    return promise;
}

function callRemoteDict(url, dictionary, nothrobber, method) {
    method = method || 'POST';
    var post = Object.toQueryString(dictionary);
    return callRemote(url, post, method, nothrobber);
}

function callRemoteDictWithAddress(url, dictionary, nothrobber, method) {
    method = method || 'POST';
    if(!dictionary) {
        dictionary = {};
    }
    // if('address_dict' in dictionary) {
    //     write('address_dict already set! protocol fail!');
    // } else {
    //     dictionary['address_dict'] = controller.serialize();
    // }
    return callRemoteDict(url, dictionary, nothrobber, method);
}

function replace_with_response(target_div) {
    return replace_with_response_text(target_div, true);
}

function replace_with_response_text(target_div, isResponse) {
    return function(o) {
        if(isResponse) 
            $(target_div).update(o.responseText);
        else
            $(target_div).update(o);
        after_dom_update(target_div);
    };
}

function replace_with_response_and_show(target_div) {
    return function(o) {
        var tmp = $(target_div);
        tmp.innerHTML = o.responseText;
        tmp.show();
        after_dom_update(target_div);
    };
}

function do_after_dom_update(node) {
    load_prefilled_textfields();
    load_tooltips();
    GlobalUpdater.updateAjaxLinks();
}

function after_dom_update(node) 
{
    if(node)
        YAHOO.util.Event.onContentReady(node, do_after_dom_update.curry(node));
    else
        do_after_dom_update(node);      
}

function load_disappearing_textfields()
{
    try {
        var nodes  = YAHOO.util.Selector.query('[rel="disappearing_textfield"]');
        var i = 0;
        var len = nodes.length;
        for(i=0; i<len; i++) {
            nodes[i].onclick = function() {
                this.select(); 
            };   
        }
    } catch(e) {}
}


function fix_position_and_show(elem, label) {
    /* IE speibt sich hier manchmal an, ist aber ein Fehler in Prototype... */
    try { 
        Position.clone(elem, label, {
            setHeight: false, 
            setWidth: false
          });
       //Element.show(label);
    } catch(e) {}
}

function get_label_for_elem(elem) {
    var a = 'label[for="' + elem.id + '"]';
    var label = null;
    if (elem.parentElement) {
        var parentt = elem.parentElement;
        label = YAHOO.util.Selector.query(a,parentt)[0];
    } else {
        label = YAHOO.util.Selector.query(a)[0];
    }
    label = YAHOO.util.Selector.query(a)[0];
    return label;
}

function fix_prefilled(elem, label) {
    if (elem.value.length == 0) {
        setTimeout(fix_position_and_show.curry(elem, label), 0);
    } else {
        Element.hide(label);
    }
}

var iccc = 0;

function _load_prefilled_textfields() {
        iccc++;
        var nodes = YAHOO.util.Selector.query('.prefilled_textfield');
        var i = 0;
        var len = nodes.length;
        for(i=0; i<len; i++) {
            var elem = nodes[i];
            make_prefilled(elem);                   
        }
}

function load_prefilled_textfields() {
    if (YAHOO.env.ua.ie > 0) {
        callDelayed('load_prefilled_textfields', _load_prefilled_textfields, 1000);
    } else {
        _load_prefilled_textfields();
    }
}

YAHOO.util.Event.addListener(window, 'resize', load_prefilled_textfields);

function make_prefilled(elem) {
    //print("make prefilled");
    //print(elem);
    YAHOO.util.Event.purgeElement(elem); 
    var label = get_label_for_elem(elem);

    fix_prefilled(elem, label);

    function listener(x) {
        if (keycode_allowed(x.keyCode)) {
            fix_prefilled(this, label);
        }
    };
    var event_names = ['change', 'keyup'];
    
    loop(event_names, function(index, event_name) {
        YAHOO.util.Event.addListener(elem, event_name, listener);
    });
    
    
    loop(['click', 'keydown', 'focus'], function(i,a) {
        YAHOO.util.Event.addListener(elem, a, function(x) {
            //if(keycode_allowed(x.keyCode)) {
                Element.hide(label);            
            //}
        });
    });
    
     YAHOO.util.Event.addListener(elem, 'blur', function(x) {
       if(elem.value.length === 0) {
           Element.hide(label);
           fix_prefilled(elem, label);
           Element.show(label);
       } 
    });
    
}

/*
 *
 * Array comparison for the rest of us.
 * from: http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
 *
 */
Array.prototype.compare = function(testArr) {
    if (this.length != testArr.length) return false;
    for (var i = 0; i < testArr.length; i++) {
        if (this[i].compare) { 
            if (!this[i].compare(testArr[i])) return false;
        }
        if (this[i] !== testArr[i]) return false;
    }
    return true;
};

var callDelayedTimers = [];
function callDelayed(name, fun, timeout) 
{
    var timer = callDelayedTimers[name];
    if(timer) {
        clearTimeout(timer);
        delete callDelayedTimers[name];
        callDelayedTimers[name] = null;
    }
    callDelayedTimers[name] = setTimeout(fun, timeout);
}

function load_order_autocomplete()
{
    
    var street_id = "order_form_street";
    var zip_id = 'order_form_zip_code';
    var number_id = 'order_form_street_number';
    var autocompleter_choices_id = 'street_auto_complete_choices';
    var check = false;
    
    Element.clonePosition(autocompleter_choices_id, street_id, {
        setHeight: false, 
        setWidth: false,
        offsetTop:15
      });
    
    
    return new Ajax.Autocompleter(
         street_id, 
         autocompleter_choices_id, 
         "/ajax/geo/city/street/", { 
             paramName: "address",
             afterUpdateElement: function() {                  
                    var street_input = $(street_id);
                    try {
                        var components = street_input.value.split(', ');
                        var street = components[0];
                        var plz = components[1].substring(0,5); 
                        street_input.value = street;
                        // $(zip_id).value = plz;
                    } catch(e) {}
             },
             indicator: 'indicator1',
             frequency: 0.05,
             callback: function(node, querystring) {
                 return (querystring +'&'+ Object.toQueryString({'district': $F('order_form_district')}));
             }
         }
    );
}


var sections_visible = true;
function toggle_menu_sections() {
    $$('.menu_section_content').each(function(e) {
        hide_or_show_section(e, sections_visible);
    });
    sections_visible = !sections_visible;
    if(sections_visible) {
        hidden_menu_section_contents = [];
    }
    
    return false;
}

function rotfl(id) {
    var section = $(id);
    if(typeof section.ausgeklappt == 'undefined') {
        if(section.id == 'menu_section-top10') {
            section.ausgeklappt = false;            
        }
        section.ausgeklappt = true;
    }
    if(section.ausgeklappt) {
        $$('#'+id +' .description').each(function(e) {
            e.hide(); 
        });
        
        $$('#'+id+' img.expandarrow').each(function(e) {
            e.src = "/media/img/sherpas/triangle_right.png";
        });
        section.ausgeklappt = false;
    } else {
        if(section.collapsed) {
            expand_collapse(id);
        }

        $$('#'+id +' .description').each(function(e) {
            e.show(); 
        });
        $$('#'+id+' img.expandarrow').each(function(e) {

            e.src = "/media/img/sherpas/triangle_down.png";
        });
        section.ausgeklappt = true;
    }
}

function hide_or_show(element, show) {
    if(!$(element))
        return;
    if(show)
        Element.show(element);
        
    else
        Element.hide(element);
}


var hidden_menu_section_contents = [];
function hide_or_show_section(section, show) {
    if(show) {
        section.hide();
        $('collapse_link').innerHTML = 'Karte aufklappen';
        hidden_menu_section_contents.push(section);
    } else {
        section.show();
        $('collapse_link').innerHTML = 'Karte zuklappen';
    }
}

/* preload_images (non-blocking version) */
function preload_images(images) 
{
    var url = images.pop();
    if(!url)
        return;
        
    var image = new Image();
    image.src = url;
    image = null;
    setTimeout(preload_images.curry(images), 0);
}


function insert_conversion_iframe() {
 var iframe = new Element('iframe',
    {
     'style': 'border-style:none; border:0px, 0px',
     'frameBorder': '0',
     'framespacing': '0',
     'border': '0',
     'scrolling': 'no',
     'id': 'conversion_iframe',
     'src': '/tracking/'
    });
    $('conversion_iframe_container').appendChild(iframe);     
}
 
 
function log(message) {
    $('log_messages').innerHTML = $('log_messages').innerHTML + "<br/>" + message;
}

function loop(dict, fun) {
    for(var key in dict) {
        if(YAHOO.lang.hasOwnProperty(dict, key))
            fun(key, dict[key]);
    }
}

/* 
 * taken from http://ajaxian.com/archives/detecting-ie7-in-javascript 
 */
function IE6() {
    if (typeof document.body.style.maxHeight != "undefined") {
      // IE 7, mozilla, safari, opera 9
          return false;
    } else {
      // IE6, older browsers
          return true;
    }
}


function delete_address(pk, address, node_id)
{
    analytics('delete_address');
    if(confirm(interpolate(gettext('Bist du sicher, dass du diese Adresse löschen möchtest?\n%s'), [address]))) {
        Element.remove(node_id);
        var promise = callRemoteDict('/ajax/customer/address/delete/', {pk: pk});
    }
}

function setCityFromGeo(location, actually_set) {
	if(!location)
		return;
	
	var geocoder = new GClientGeocoder();

	var point = new GLatLng(location.latitude, location.longitude);

	geocoder.getLocations(point, function(addresses) {
		if(addresses.Status.code != 200) {
			write("reverse geocoder failed to find an address for " + point.toUrlValue());
			locate_error();
			return;
		}
		else {
			var place = addresses.Placemark[0];
			try {
				if ('SubAdministrativeArea' in place.AddressDetails.Country.AdministrativeArea) {
					var city  = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
					   
				} else {
					var city  =  place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;    
				}
			} catch(e) {
				var city = '';
			}

			try {
				var zip_code = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.PostalCode.PostalCodeNumber;
			} catch(e) {
				var zip_code = '';
			} 
			try {
				var thoroughfare = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.DependentLocality.Thoroughfare.ThoroughfareName;
			} catch(e){
				var thoroughfare = '';
			}

			var re = /([^\d]*)(\d*)/;
			var street = re.exec(thoroughfare)[1];
			try {
				var number = re.exec(thoroughfare)[2];                
			} catch(e) {
				var number = '';
			}
			
			try {
				  var country_code = place.AddressDetails.Country.CountryNameCode.toLowerCase();                  
			} catch(e) {
				locate_error();
				return;
			}

			try {
				// here the address state of the controller should be changed but the code has to be rewritten down there an we don't use it anymore
				// if(slugify(city) in controller.cities) {
				// 	if(actually_set) {
				// 		var city2 = controller.cities[city_slug];
				// 		controller.setCity(city2.display_name, city2.slug, city2.country_code, false);
				// 	} else {
				// 		controller.located_city = controller.cities[slugify(city)];
				// 		// HTIS IS NOW IN SEARCH WIDGET !!!!!!!1
				// 		// this.showLocatedCityMessage();
				// 	}
				// }
				// 
				// this.showLocatedCityMessage = function() {
				// 	if(controller.located_city && ( controller.city_slug != controller.located_city.slug ) ) {
				// 		var tmp = {city_located: gettext(controller.located_city.display_name), city_located_slug: controller.located_city.slug, city_current: controller.cities[controller.city].display_name};
				// 		$('location_controller_message').update(interpolate(gettext('Wir denken, du bist in %(city_located)s anstatt in %(city_current)s. <a href="" onclick="return false;">Zur Restaurantliste für %(city_located)s</a>'), tmp, true));
				// 		$('location_controller_message').show();
				// 		var a = $$('#location_controller_message a')[0];
				// 		YAHOO.util.Event.addListener(a, 'click', function () {
				// 			this.setCityAndNavigate(controller.located_city.display_name, controller.located_city.slug, controller.located_city.country_code, true);
				// 			$('location_controller_message').hide();
				// 			this.hideLocatedCityMessage();
				// 		}, this, true);
				// 		
				// 	}
				// };
			} catch(e) {}
		}
		Throbber.release();
	}.bind(this));
};

function loki_locate_error()
{
    analytics('skyhook/error');
    Throbber.release();
    setCityFromGeo(google.loader.ClientLocation);
    GrowlMessage(gettext('Dein genauer Standort konnte nicht automatisch bestimmt werden. Bitte gib deine Adresse manuell ein.'));
}

function locate_error() 
{
    write('google/locateError');
    analytics('google/locateError');
}

function onMainPage() {
    var h = document.location.hash;
    return (h == '' || h == '#page=landing');
}


function initLoader()
{
    if(typeof google != 'undefined') {
        google.load("maps", "2", {"language" : "en_EN", 'callback': locate});        
    }
}

var locate_was_called_manually = false;
function locate() {
    if(!controller.address.zip_code) {
        setCityFromGeo(google.loader.ClientLocation, onMainPage());
    }
}

function slugify(string) 
{
    string = string.toLowerCase();
    var replace = {
        ' ': '',
        'ü': 'u',
        'ä': 'a',
        'ö': 'o',
        'ß': 'ss',
        'munich': 'munchen',
        'wien': 'wien'
    };
    loop(replace, function(key, value){
       string = string.gsub(key, value); 
    });
    return string;
}


function str(x) {
    return x.__str__();
}


function button_show_more() {
    $('restaurant_list_footer').hide();
    $$('.delivery_group').invoke('show');
    
}

var mjam_lightbox_object = null;

function mjam_lightbox(title, body, buttons, classname, uglytable) {
    var div = new Element('div');
    if (!classname) {
        div.addClassname(classname);
        var lightbox = new Lightbox(div, classname);
    } else {
        var lightbox = new Lightbox(div);
    }
    mjam_lightbox_object = lightbox;

    classname = classname || "mjam_lightbox";
    uglytable = uglytable || true;

    div.update('<div class="'+classname+'"><a class="lightboxCloser lightboxCloserRed" onclick="mjam_lightbox_object.hide();return false;"></a><div class="title ligthboxTitle red">'+title+'</div><div class="body fliesstextL">'+body+'</div>');

    var cancel_function = function(e) {
        lightbox.hide();
        return false;
    };

    var buttons_container = new Element('div', {'class': 'lightbox_button_container'});
    
    for (i=0; i<buttons.length; i++) {
        button = buttons[i];

        // default values
        if (button.text==undefined)      button.text = "Mjam Button";
        if (button.classname==undefined) button.classname = classname + "_" + button.text.replace(/[ \t\r\n]+/g, "_");
        if (button.callback==undefined)  button.callback = cancel_function;
        if (button.type==undefined)      button.type = "a";

        // wrap table around button
        if (uglytable) button.text = interpolate('<table border="0"><tr><td class="sliceLeft"></td><td class="sliceCenter">%s</td><td class="sliceRight"></td></tr></table>', [button.text]);

        // add button to DOM
        var elbutton = new Element(button.type, {'class': button.classname});
        elbutton.update(button.text);
        buttons_container.appendChild(elbutton);
        Event.observe(elbutton, "click", button.callback.bindAsEventListener(this));
    }

    div.appendChild(buttons_container);
    lightbox.show(false, 'lightbox ' + classname);
}




function branch_closed_lightbox(restaurant_nurl, restaurant_name, regular_charge, current_charge, scroll_to_item) {    
    // load code from the template
    var html = $('branch_warning_lightbox_template').innerHTML;
    
    html = interpolate(html, {
        restaurant_name: restaurant_name,
        higher_delivery_fee: current_charge
    }, true);
    
    var e = new Element('div');
    var lightbox = new Lightbox(e);
    e.update(html);
        
    var cancel_button = new Element('a', {'class': 'buttonSecondary'});
    var preorder_button = new Element('a', {'class': 'buttonPrimary'});
    var order_now_button = new Element('a', {'class': 'buttonPrimary'});

    cancel_button.update(
        interpolate('<table border="0"><tr><td class="sliceLeft"></td><td class="sliceCenter">%s</td><td class="sliceRight"></td></tr></table>', [gettext('Cancel')])    
    );
    
    preorder_button.update(
        interpolate('<table border="0"><tr><td class="sliceLeft"></td><td class="sliceCenter">%s</td><td class="sliceRight"></td></tr></table>', [gettext('Preorder')])    
        );

    order_now_button.update(
        interpolate('<table border="0"><tr><td class="sliceLeft"></td><td class="sliceCenter">%s</td><td class="sliceRight"></td></tr></table>', [gettext('Order now')])    
    
    );
    
    e.appendChild(cancel_button);
    e.appendChild(preorder_button);
    e.appendChild(order_now_button);

    var cancel_function = function(e) {
        lightbox.hide();
        return false;
    };
    
    var preorder_function = function(e) {
        lightbox.hide();
        return false;
    };
    
    var order_now_function = function(e) {
        if(scroll_to_item) {
            scroll_to_menu_item = scroll_to_item;
        }
        document.location = restaurant_nurl;
        return false;
    };

    Event.observe(cancel_button, "click", cancel_function.bindAsEventListener(this));
    Event.observe(preorder_button, "click", preorder_function.bindAsEventListener(this));
    Event.observe(order_now_button, "click", order_now_function.bindAsEventListener(this));
    
    
    lightbox.show(false, 'branch_closed_lightbox lightbox');
    
}

function reload_with_district (district) {
    controller.setAddress({district: district}, null, function() {
        var canonical_tag = $$('link[rel=canonical]')[0];
        if(canonical_tag && document.location.href != canonical_tag.href) {
            redirect(canonical_tag.href);
        } else {            
        	document.location.reload(true);
        }
	});
}

function coming_soon_lightbox(restaurant_nurl, restaurant_name) {
    mjam_lightbox(
        gettext('Coming Soon!'),
        gettext('This Restaurant will be available soon.'),
        buttons = [
            {
                text : 'Go back to list',
                type : 'span',
                classname : "currently_closed_lightbox_cancel"
            }
        ],
        classname = "coming_soon_lightbox"
    );
}

Event.observe(document, 'click', function(e) {
    var closeIfOpen = function(elem) {
        if(Event.element(e) === elem) {
            return;
        }
        var shouldReturn = false;
        loop(Event.element(e).ancestors(), function(i, rofl) {
            if(rofl === elem) {
                shouldReturn = true;
            }
        });
        if(shouldReturn) {
            return;
        }
        elem.removeClassName('clicked');
    };
    
    loop($$('.select_click.clicked'), function(i, elem) { closeIfOpen(elem); });
    loop($$('.withaction_click.clicked'), function(i, elem) { closeIfOpen(elem); });
}, false);




function toggle_comment_box(id) {
    $(id).toggle();
}

function toggle_top_cities() {
    $('frontpage_cities_all').toggle();
    var button = $('frontpage_cities_toggle_button');
    if(button.expanded) {
        button.innerHTML = gettext('Aufklappen…');
        button.expanded = false;        
    } else {
        button.innerHTML = gettext('Zuklappen…');
        button.expanded = true;
    }
}


function redirect(target) {
    document.location = target;
}

function submit_suggestion () {
    var promise = callRemote('/ajax/discuss/suggestion/', Form.serialize($('empty_search_form')));
    promise.addCallback(WidgetCenter.get('zip_not_found_lightbox').hide());
}



function build_url_willessen_aware(zip_code) {
    if(zip_code[0] == '1') {
        // wien
        var bezirk_id = (parseInt(zip_code, 10) - 1000)/10;
    }  else {
        var bezirk_id = zip_code;
    }
    var url = '/restaurants.php?bez=' + bezirk_id;
    return url;
}
 

function urljoin(a, b) {
    var absolute = (a[0] == '/');
    var A = a.split('/');
    var B = b.split('/');
    
    var url = A.concat(B).filter(function(x) {return x;}).join('/') + '/';
    if(absolute) {
        url = '/' + url;
    }
    return url;
}


function isMobileSafari(){
    return (
        navigator.platform.indexOf("AppleWebKit") != -1 &&
        navigator.platform.indexOf("Mobile") != -1
    
    );
}

