var widgets = [];

var Widget = function(widget, options) {
	this.element = $(widget);

    this.type = null;

    var type = (" " + this.element[0].className + " ").match(/ widget +(\w+)/);
    type = type ? type[1] : null;

	this.add();

	var pos;
	if (!options)
		options = {};

	if (!options.col || options.index == undefined)
	{
		pos = this.placement(true);
	}

	this.dom = this.element[0];
	this.shaded = this.element.is('.shaded');
	this.col = options.col || pos.col;
	this.index = options.index != undefined ? options.index : pos.index;
	this.id = options.id || 0;
    this.type = type;

	this.handle_title(this.element);

	if (!options.no_init)
	{
		handle_toolbar(this.element);
		Actions.apply(this.element);
	}
	if (this.shaded)
	{
		var img = $('div.title div.toolbar .shade img', this.element)[0];
		img.src = img.src.replace('minimize.gif', 'maximize.gif');
	}


	return this;
}

Widget.prototype.placement = function(slow) 
{
	if (!slow)
		return { 
			col: this.col, 
			index: this.index 
		}
	
	return {
		id: this.id,
		col: $(COLUMN_SELECTOR).index(this.element.parent()) + 1 + (window.START_COLUMN ? window.START_COLUMN - 1 : 0),
		index: this.element.parent().find(WIDGET_SELECTOR).index(this.element)
	}

}

Widget.prototype.add = function() 
{
	if ($(COLUMN_SELECTOR).index(this.element.parent()) != -1)
	{
		return;
	}

	var cols = $(COLUMN_SELECTOR);
	cur_col = cols.length;
	$(cols[Math.min(1, cur_col - 1)]).prepend(this.element);

	$('#widgetcontainer').children('div.column').sortable("refresh");
	this.element.addClass('new');
}

Widget.prototype.handle_title = function() 
{
	var header = $('> div.title > h2', this.element);
    var title = $('> span:first', header);

	header.attr('title', 'Dra mig! - Genom att trycka och hålla nere musknappen kan du flytta ditt innehåll.');

    var link = $('> span a', header);
    if (link.length)
    {
        link.before(link.html())[0].style.display = "none";
        header.append(link);
    }

    var override = $('> span.override', header);
    var o_text = $.trim(override.text().replace('\240', ' ')); // \240 == &nbsp;

    title[0].origText = $.trim(title.html());
	if (o_text)
	{
        title.html(o_text);
	title[0].curText = o_text;
	}
}

Widget.prototype.move = function(id, col, index) 
{
    if (window.DUMMY) return dummy();

	this.element.width('auto');

	if (!col || (this.col == col && this.index == index))
	{
		manager.reorder()
		return;
	}

	var old_p = { col: this.col, index: this.index };

	var url = resolve_url(this.element, [ '/move', 0, col, index, '?ajax' ].join('/'), true);

	this.col = col;
	this.index = index;

	var self = this;

	$('#widgetcontainer').children('div.column').sortable("refresh");

	$.ajax({ url: url, 
		widget: this.element,
		type: 'post',
		data: { '_': 1 },
		success: function(data) { 
			manager.reorder() 
			update_modified(data);
		}, 
		error: function(request) { // Move back
			widget_error(self.element, request);

			var column = $(COLUMN_SELECTOR).get(old_p.col - 1);

			if ((old_p.col == self.col) && (old_p.index > self.index))
				old_p.index += 1;

			if (old_p.index == 0)
				$(column).prepend(self.element);
			else
				$($(WIDGET_SELECTOR, column).get(old_p.index - 1)).after(self.element);

			manager.reorder();
			$('#widgetcontainer').children('div.column').sortable("refresh");
		}
		});
}

/* **************** *
 *   WidgetManager  *
 * **************** */ 

var WidgetManager = function() 
{
	this.types = {};
    var self = this;

    this.clear_widgets();

    $(function() {
	    self.ie_resizebug();
	    $(window).resize(function() {
		self.handle_resize();
	    });
    });
}

WidgetManager.prototype.clear_widgets = function() 
{
    this.widgets = [];
    this.domcache = [];
}

WidgetManager.prototype.init_types = function() 
{
	for (type in this.types)
	{
		if (this.types[type].init)
			this.types[type].init();
	}
}

WidgetManager.prototype.ie_resizebug = function() 
{
    if ($.browser.msie) // ie fires resize event on body/dom change
    {
	    var w = $(window).width();
	    var h = $(window).height();

	    if ((this.ie_resize_height == h)
			    && (this.ie_resize_width == w))
		    return true;

	    this.ie_resize_width = w;
	    this.ie_resize_height = h;
    }
    return false;
}

WidgetManager.prototype.handle_resize = function() 
{ 
    if (this.ie_resizebug())
	    return;

    var self = this;
    $.each(self.widgets, function(i) {
        var resize_fn = self.types[this.type].resize;
        if (resize_fn)
        {
            resize_fn(this);
        }
    });
}

WidgetManager.prototype.init_widgets = function()
{
    var self = this;
    var WIDS = window.WIDGET_IDS || [];

    $(COLUMN_SELECTOR).each(function(col) { 
	var ids = (WIDS.length > col) ? WIDS[col] : [];

        col += window.START_COLUMN ? window.START_COLUMN - 1 : 0;
        $(WIDGET_SELECTOR, this).each(function(i) { 
		var id = (ids.length > i) ? ids[i] : 0;

		var w = new Widget(this, { col: col + 1, index: i, id: id, no_init: true });
		self.widgets.push(w);
		self.domcache.push(this);

        self.init_widget(w);
	});
    });
}

WidgetManager.prototype.new_widget = function(widget)
{
    if (!$('#widgetcontainer').length) // Not startpage
    {
        location.href = '/';
        return;
    }

	var w = new Widget(widget);
	this.widgets.push(w);
	this.domcache.push(w.dom);

	widget.width(WIDGET_WIDTH);

    this.init_widget(w);
	$.scrollTo(widget, 400, { 
		over: { top: -0.3 }
	});
}

WidgetManager.prototype.init_widget = function(widget)
{
    var w = widget;
    if (w.jquery)
        w = this.find(w);

    if (!w)
        return;

	if (this.types[w.type])
	{
		if (this.types[w.type].init_widget)
			this.types[w.type].init_widget(w);
	}
	else
		this.types[w.type] = {};

    if ($('div.redirect', w.element).length) // Reload widget by using new request
    {
        $('div.redirect a', w.element).each(Actions.linkclick);
        return;
    }
}

WidgetManager.prototype.find = function(widget, index) 
{
    if (index !== undefined) // search by col, index
    {
        var col = widget;
        for (var i = 0; i < this.widgets.length; i++)
        {
            var w = this.widgets[i];
            if (w.col == col && w.index == index)
                return w;
        }
        return null;
    }

	if (widget.jquery)
		widget = widget[0];

	var i = $.inArray(widget, this.domcache);
	return i == -1 ? null : this.widgets[i];
}

WidgetManager.prototype.remove_widget = function(widget) 
{
	if (widget.jquery)
		widget = widget[0];

	var i = $.inArray(widget, this.domcache);
	if (i != -1)
	{
		this.widgets[i].element.remove();
		this.widgets.splice(i, 1);
		this.domcache.splice(i, 1);
		this.reorder();
	}

	$(widget).remove();
}

WidgetManager.prototype.reorder = function() 
{
	check_dummys();

	for (var i = 0; i < this.widgets.length; i++)
	{
		var w = this.widgets[i];
		var pos = w.placement(true);

		w.col = pos.col;
		w.index = pos.index;
	}

	$('#widgetcontainer').children('div.column').sortable("refresh");
}

var manager = new WidgetManager();
;/* styles/base/js/johnlib.js */
var IE6 = ($.browser.msie && $.browser.version < 7);

function rss_init_widget(widget, force)
{
    var compact = ($('div.images', widget.dom).is('.compact'));
    var images = $('div.content img', widget.dom);

	if (IE6)
	{
        var maxwidth = Math.floor(WIDGET_WIDTH * (compact ? 0.48 : 0.8));

		var imagesize_fix = function() {

            if (!this.width)
            {
                this.style.width = "1px";
                return $(this).load(imagesize_fix);
            }
            this.style.width = "";

            if (!this.origWidth) this.origWidth = this.width;
            this.width = this.origWidth;

            if (this.width < 10)
                return $(this).parent('a').remove();

			if (this.width > maxwidth)
				this.width = maxwidth;
			if (this.height > 155)
				this.width = Math.floor(this.width * (150 / this.height));
		};
        images.each(imagesize_fix);
	}

	images.parents('a[rel]').filter(function() {
			var i = this.rel.indexOf('bg:');
			if (i != -1)
			{
				this.title = $('img', this).attr('title') + ' || <a rel="dialog" href="/style/background/?image=' + encodeURIComponent(this.rel.substring(i + 3)) + '" onclick="$(\'#cluetip\').hide()">Använd som bakgrundsbild</a>';
				return true;
			}
			}).cluetip({
				splitTitle: ' || ', 
				leftOffset: 2,
				hoverIntent: {
timeout: 3000
}
			});
    if (compact)
    {
        images.load(function() {
		if (!widget.dom.wrap_timer)
                widget.dom.wrap_timer = setTimeout(function() { rss_wrap_images(widget) }, 100);
        }).error(function() {
            $(this).parent('a').remove();
            rss_wrap_images(widget);
        });
        rss_wrap_images(widget);
    }
    
    $('a.medialink', widget.dom).unbind('click').click(function() { 
            try {
            play_song(this.href, this.title);
            } catch (e) { return; }
            return false;
            });
}

function rss_wrap_images(widget)
{
    if (IE6)
        return;

    widget.dom.wrap_timer = 0;

    var imagecontainer = $('div.images', widget.dom);
    if (!imagecontainer.is('.compact'))
        return;

    var max, min, total_width;
    max = min = total_width = 0;

    var images = [];
    $('a img', imagecontainer).each(function() {
	    if (this.complete)
	    {
		    if (this.width < 10)
			    return $(this).parent('a').remove();

		    if (this.width > max)
			    max = this.width;
		    if (this.width < min || !min)
			    min = this.width;
		    total_width += this.width;
	    }
	    images.push(this);
    });

    var existing_rows = $('> div', imagecontainer);

    var maxwidth = imagecontainer.width();

    if (!maxwidth)
        return;

    if (maxwidth > total_width)
    {
        if (existing_rows.length)
        {
            imagecontainer.append(existing_rows.children());
            existing_rows.remove();
        }
        return;
    }

    if (max && (Math.abs(max - min) <= max * 0.2)) // Display equal amount of images on each row
    {
	    var rcount = Math.max(1, Math.ceil(total_width / maxwidth));
        var image_objs = $('img', imagecontainer).parent('a');

	    if (rcount > 1)
        {
            var collapser = $('<div />').css({
                maxWidth: images.length / rcount * max + 10
            }).append(image_objs);
            imagecontainer.append(collapser);
        }
        else
            imagecontainer.append(image_objs);
	    existing_rows.remove();
	    return;
    }
}

if (window.manager)
manager.types.rss = {
    init_widget: rss_init_widget,
    resize: function(widget) { rss_init_widget(widget, 1); }
}
;/* styles/base/js/rss.js */
var IE6 = ($.browser.msie && $.browser.version < 7);

function rss_init_widget(widget, force)
{
    var compact = ($('div.images', widget.dom).is('.compact'));
    var images = $('div.content img', widget.dom);

	if (IE6)
	{
        var maxwidth = Math.floor(WIDGET_WIDTH * (compact ? 0.48 : 0.8));

		var imagesize_fix = function() {

            if (!this.width)
            {
                this.style.width = "1px";
                return $(this).load(imagesize_fix);
            }
            this.style.width = "";

            if (!this.origWidth) this.origWidth = this.width;
            this.width = this.origWidth;

            if (this.width < 10)
                return $(this).parent('a').remove();

			if (this.width > maxwidth)
				this.width = maxwidth;
			if (this.height > 155)
				this.width = Math.floor(this.width * (150 / this.height));
		};
        images.each(imagesize_fix);
	}

	images.parents('a[rel]').filter(function() {
			var i = this.rel.indexOf('bg:');
			if (i != -1)
			{
				this.title = $('img', this).attr('title') + ' || <a rel="dialog" href="/style/background/?image=' + encodeURIComponent(this.rel.substring(i + 3)) + '" onclick="$(\'#cluetip\').hide()">Använd som bakgrundsbild</a>';
				return true;
			}
			}).cluetip({
				splitTitle: ' || ', 
				leftOffset: 2,
				hoverIntent: {
timeout: 3000
}
			});
    if (compact)
    {
        images.load(function() {
		if (!widget.dom.wrap_timer)
                widget.dom.wrap_timer = setTimeout(function() { rss_wrap_images(widget) }, 100);
        }).error(function() {
            $(this).parent('a').remove();
            rss_wrap_images(widget);
        });
        rss_wrap_images(widget);
    }
    
    $('a.medialink', widget.dom).unbind('click').click(function() { 
            try {
            play_song(this.href, this.title);
            } catch (e) { return; }
            return false;
            });
}

function rss_wrap_images(widget)
{
    if (IE6)
        return;

    widget.dom.wrap_timer = 0;

    var imagecontainer = $('div.images', widget.dom);
    if (!imagecontainer.is('.compact'))
        return;

    var max, min, total_width;
    max = min = total_width = 0;

    var images = [];
    $('a img', imagecontainer).each(function() {
	    if (this.complete)
	    {
		    if (this.width < 10)
			    return $(this).parent('a').remove();

		    if (this.width > max)
			    max = this.width;
		    if (this.width < min || !min)
			    min = this.width;
		    total_width += this.width;
	    }
	    images.push(this);
    });

    var existing_rows = $('> div', imagecontainer);

    var maxwidth = imagecontainer.width();

    if (!maxwidth)
        return;

    if (maxwidth > total_width)
    {
        if (existing_rows.length)
        {
            imagecontainer.append(existing_rows.children());
            existing_rows.remove();
        }
        return;
    }

    if (max && (Math.abs(max - min) <= max * 0.2)) // Display equal amount of images on each row
    {
	    var rcount = Math.max(1, Math.ceil(total_width / maxwidth));
        var image_objs = $('img', imagecontainer).parent('a');

	    if (rcount > 1)
        {
            var collapser = $('<div />').css({
                maxWidth: images.length / rcount * max + 10
            }).append(image_objs);
            imagecontainer.append(collapser);
        }
        else
            imagecontainer.append(image_objs);
	    existing_rows.remove();
	    return;
    }
}

if (window.manager)
manager.types.rss = {
    init_widget: rss_init_widget,
    resize: function(widget) { rss_init_widget(widget, 1); }
}
;/* styles/base/js/rss.js */
function blocket_submit(ev)
{
    var widget = get_widget(this);
    var area = $('option[selected]', $('select[name=area]', widget))[0].value;
    var category = $('option[selected]', $('select[name=category]', widget))[0].value;

    this.href = 'http://www.blocket.se/li?ca=' + 
        (area ? area : 'ca=11&w=3') + '_s' +
        (category ? '&cg=' + category : '');
}

if (window.manager)
manager.types.blocket = {
    init_widget: function(widget) {
        $('a.outlink', widget.dom).mousedown(blocket_submit);
    }
};
;/* styles/base/js/blocket.js */
function search_select_engine()
{
	var widget = get_widget(this);

	var existing = $('.picker', widget);
	if (existing.length)
	{
		existing.remove();
		return false;
	}

	var picker =  $('<ul class="popup picker" />');
	var link = $(this);

    picker.hover(function() {
        clearTimeout(picker.timer);
    },
    function() {
        picker.timer = setTimeout(function() { picker.remove() }, 1000);
    });
	var forms = $('form', widget);
	forms.each(function(i) {
		var engine = $('<li />');
		engine.append($('span', this).clone().removeClass('noscript'));
		engine.hover(function() { engine.addClass('hover'); }, function() { engine.removeClass('hover') });
		engine.click(function() {
			var chosen = $('form.chosen', widget);
			chosen.removeClass('chosen').hide();

			$(forms[i]).addClass('chosen').show();
            var id = forms[i].id.substring('engine'.length);
            setTimeout(function() {
		    $.post(resolve_url(widget, 'settings/'), { 'default_engine': id });
	    }, 500);

			$('input:text', forms[i]).blur();
			$('input:text:eq(0)', forms[i]).val($('input:eq(0)', chosen).focus().val()).focus();

			picker.remove();
		});
		picker.append(engine);
	});

	picker.css({
		position: 'absolute',
		zIndex: 90,
		marginTop: link.height() + 4
	});

	$(this).before(picker);

	return false;
}

var search_is_focused = false;
function search_init_widget(widget)
{
	$('span.engine', widget.dom).click(search_select_engine);

	$('input:text', widget.dom).focus(function() {
		if (this.value == this.title)
			this.value = '';
	}).blur(function() {
		if (!this.value)
			this.value = this.title;
	});

    var forms = $('form', widget.dom);
	forms.submit(function() {
                this.target = (window.USE_SAME_WINDOW) ? "" : '_blank';
		$('input:text', this).focus();
	});

	forms.each(function(i) {
		$('input:text', this).keydown(function(ev) {
			if (!ev.ctrlKey)
				return;
			direction = 0;
			if (ev.keyCode == 38 && i > 0) // up
				direction = -1;
			else if (ev.keyCode == 40 && i < forms.length - 1) // down
				direction = 1;

			if (!direction) return;

			$('span.engine:eq(0)', forms[i]).click();
			var picker = $('.picker', widget.dom);
			$($('li', picker)[i + direction]).click();
		});
	});

    var first_form = $(forms).filter(':first').addClass('chosen');
    if (!search_is_focused)
    {
        var input = $('input[type=text]:eq(0)', first_form);
        if (input.offset().top < $(window).height()) input.focus();
        search_is_focused = true;
    }
}

if (window.manager)
manager.types.search = {
init_widget: search_init_widget
};
;/* styles/base/js/search.js */
function init_facebook_widget(widget)
{
    widget = get_widget(widget.dom);

    var pre = $('.pre-login', widget);
    if (!pre.is('a'))
        pre = $('a:eq(0)', pre);

    var post_login = $('.post-login', widget);

    pre.mousedown(function() {
        post_login.css('display', 'block');
        return false;
        $(this).css('opacity', 0.5);
    });

    pre.unbind('click').click(function() {
        var win = window.open(this.href, 'fb', 'toolbar=no,menubar=no,width=640,height=480');
	if (!win)
		return true;
	win.focus();

        facebook_watch_popup(win, function() {
            $(post_login.is('a') ? post_login : $('a', post_login)[0]).each(Actions.linkclick);
        });

        return win ? false : win;
    });

    var userinfo = $('div.userinfo', widget);
    if (userinfo.length)
    {
        var s = $('span.status', userinfo);
        var edit_link = $('a.edit', userinfo);

        edit_link.click(function() { s.click(); return false; });

        if (s.is('.disabled'))
            s.click(function() {
                    var win = window.open(edit_link[0].href, 'fb', 'toolbar=no,menubar=no,width=640,height=480');
		    if (!win) 
			    return true;
		    win.focus();
                    facebook_watch_popup(win, function() {
                        Actions.reload_inner.call(widget, 'render/?status_update=1');
                    });
                    return false;
            });
        else s.editable(function(value) {
            var orig = this.revert;
            $.ajax({
                url: resolve_url(widget, 'set_status/'), 
                data: { value: value },
                type: 'post',
                success: function(data) {
                    if (data.substring(0, 7) == "DENIED:")
                    {
                        var msg = $('<p><strong>Behörighet saknas!</strong><br />&raquo; <a href="' + data.substring(7) + '" rel="popup">Tillåt statusändringar</a> &laquo;</p>');
                        Actions.apply(msg);
                        $('a', msg).click(function() { s.show(); msg.remove(); });
                        s.before(msg).hide();

                        $('strong', msg).effect("highlight", { color: '#ff0000'}, 2000);
                        s.html(orig);
                    }
                },
                error: function() {
                    s.html(orig);
                }
            });
            return value;
        }, 
        { 
            submit: 'spara',
            placeholder: 'is ...'
        });
    }
}

function facebook_watch_popup(win, callback) 
{
    if (win.closed)
    {
        callback();
        return;
    }
    setTimeout(function() { facebook_watch_popup(win, callback); }, 1000);
    return;
}



if (window.manager)
manager.types.facebook = { 
    init_widget: init_facebook_widget
}
;/* styles/base/js/facebook.js */
function init_linker_widget(widget)
{

    var linktext = '<a class="remove noscript" href="#" class="reloadinner">[x]</a>';

    var setup_removelink = function(key, value) {
        var col = $(this);
        var link = $(linktext).appendTo(this);
        link.click(function() {

                data = {}; data[key] = value;

                widget.element.addClass('loading');
                $.post(resolve_url(widget.dom, 'settings/'),
                    data,
                    function(data) {
                        set_content(widget.dom, data);
                    }
                    );

                return false;
                });

        $(this).hover(function() {
                link.show();
            }, function() {
                link.hide();
            });
    }

    if ($('tr.banks', widget.dom).length > 1)
        $('tr.banks td.icon', widget.dom).each(function(i) {
            var id = $('a[rel]:first', this).attr('rel').replace(/.*b\[(\d+)\].*/, '$1');
            setup_removelink.call(this, 'remove_bank', id);
        });
    $('tr.link td.icon', widget.dom).each(function(i) {
            setup_removelink.call(this, 'remove', i);
        });

    var addrow = $('.add-link', widget.dom);
    var form = $('form', widget.dom);
    if (form.length)
    {
        var link = $('<a href="#">' + form.attr('title') + '</a>');
        link.insertBefore(form).click(function() {
                form.toggle();
                return false;
                });
    }

}



if (window.manager)
manager.types.linker = { 
    init_widget: init_linker_widget
}
;/* styles/base/js/linker.js */
function iframer_init_widget(widget)
{
    if ($.browser.msie)
        $('iframe', widget.dom).each(function() { 
            this.frameborder = 0;
            this.scrolling = this.style.overflow;
        });
}

if (window.manager)
manager.types.iframer = {
    init_widget: iframer_init_widget
};
;/* styles/base/js/iframer.js */
function radio_init_widget(widget)
{
	$('form', widget.dom).submit(function() {
        var data = $('select, input', this).serialize();

        $.post(resolve_url(widget.dom, 'settings/'), { 'channel': $('select', this).val() });

        return !window.open(this.action + '?' + data, 'radio',
            'width=735,height=500,scroll=no,statusbar=no,toolbar=no');
    });
}

if (window.manager)
manager.types.radio = {
    init_widget: radio_init_widget
};
;/* styles/base/js/radio.js */
function email_settings_items(widget, menu) {
    var items = $('<li>Konfigurera konton</li>');
    items.click(function() { 
        Actions.reload_inner.call(widget, 'account_settings/')  
        menu.remove();
        });

    return items;
}

function email_init_widget(widget)
{
	var rows = $('form.account-settings table tr', widget.dom); // Account settings
	if (!rows.length)
		return;

	var advanced = $(rows.slice(-2));
	var toggler = $('<tr><td></td><td><a href="#">Avancerat</td></tr>');
	$(advanced[0]).before(toggler);
	$('a', toggler).click(function() { advanced.toggle(); return false; });
	advanced.hide();
}

if (window.manager)
manager.types.emailchecker = {
    settings_items: email_settings_items,
    init_widget: email_init_widget
};
;/* styles/base/js/emailchecker.js */
function notes_init_widget(widget)
{
    $('form', widget.dom).each(function() {
	var $form = $(this);

        var pre = $('<div class="notecontent"></div>');
        var textarea = $('textarea', this);

	var text_content = textarea.html();
	$form.data('orig_text', text_content);

        pre.html(notes_get_html(text_content, widget)).css('height', textarea.css('height'));

        $(this).before(pre);

        var old_overflow = pre.css('overflowX');

        pre.editable(resolve_url(widget.dom, this.action + '?only_text=1'), {
            name: 'text',
            onblur: 'submit',
            type: 'textarea',
            width: '100%',
            callback: function(html) {
                pre.css('overflowX', old_overflow).html(notes_get_html(html, widget));
		$form.data('orig_text', html);
            },
            data: function(html, settings)
            {
                pre.css('overflowX', 'visible');
                settings.target = resolve_url(widget.dom, $form[0].action + '?only_text=1');
                return $form.data('orig_text');
            }
        });
    }).remove();
}

var notes_url_replace = /(?:http:\/\/|(www\.))([^ ^\n^<]+)/gi;

function notes_get_html(input, widget)
{
	var max_chars = Math.min(Math.floor($(widget.dom).width() / 8), 100);
	var char_replace = new RegExp("([a-z0-9]{" + max_chars + "})", "gi");

	return input.replace(
	notes_url_replace, '<a onclick="return false;" href="http://$1$2">$1$2</a>').replace(
	char_replace, '$1-\n').replace(
	/(\r\n|\n|\r)/g, "<br />");
}

function notes_settings_items(widget, menu)
{
	items = $('<li>Skriv ut</li>');
	items.click(function() { 
		Actions.popup.call({ href: resolve_url(widget, 'print/', true) })
	});

	return items;
}

if (window.manager)
    manager.types.notes = {
        init_widget: notes_init_widget,
	settings_items: notes_settings_items
    }
;/* styles/base/js/notes.js */
function video_init_widget(widget)
{
    var player = $('object', widget.dom);
    if (!player.length)
        return;

    player.data('ratio', player[0].width / player[0].height);

    video_resize(widget);
}

function video_resize(widget)
{
    var player = $('object', widget.dom);

    var new_x = Math.floor(player.parent().width());
    var new_y = Math.floor(new_x / player.data('ratio'));

    if (new_y > 272)
    {
        new_y = 272;
        new_x = Math.floor(new_y * player.data('ratio'));
    }

    player[0].width = new_x;
    player[0].height = new_y;

}

if (window.manager)
manager.types.video = {
    init_widget: video_init_widget,
    resize: video_resize
}
;/* styles/base/js/video.js */
function tasteline_init(widget)
{
    $('input', widget.dom).click(function() {
                if (this.value == this.title) this.value = '';
            }).blur(function() {
                if (!this.value) this.value = this.title;
            }).blur();

    var recipies = $('ul.linklist', widget.dom).addClass('scripted');

    var orig_selected = $('li.selected', recipies);
    var cur = orig_selected;

    recipies.hover(function(){},
            function(ev) {
                cur.removeClass('selected');
                cur = orig_selected.addClass('selected');
            });

    $('li', recipies).mouseover(function() {
            cur.removeClass('selected');
            cur = $(this).addClass('selected');
        });
}

if (window.manager)
manager.types.tasteline = {
    init_widget: tasteline_init
};
;/* styles/base/js/tasteline.js */
function init_twitter_widget(widget)
{
    var status = $('input.status', widget.dom);
    status.click(function() {
        if (this.value == this.title) this.value = "";
    }).blur(function() {
        if (!this.value) this.value = this.title;
    }).blur();

    widget = get_widget(widget.dom);

    var pre = $('.pre-login', widget);
    if (!pre.is('a'))
        pre = $('a:eq(0)', pre);

    var post_login = $('.post-login', widget);

    pre.mousedown(function() {
        post_login.css('display', 'block');
        return false;
        $(this).css('opacity', 0.5);
    });

    pre.unbind('click').click(function() {
        var win = window.open(this.href, 'twitter', 'toolbar=no,menubar=no,width=640,height=480');
	if (!win)
		return true;
	win.focus();

        twitter_watch_popup(win, function() {
            $(post_login.is('a') ? post_login : $('a', post_login)[0]).each(Actions.linkclick);
        });

        return win ? false : win;
    });

}

function twitter_watch_popup(win, callback) 
{
    if (win.closed)
    {
        callback();
        return;
    }
    setTimeout(function() { twitter_watch_popup(win, callback); }, 1000);
    return;
}


if (window.manager)
manager.types.twitter = { 
    init_widget: init_twitter_widget
}
;/* styles/base/js/twitter.js */
function hitta_init_widget(widget)
{
	$('form', widget.dom).each(function() {
			this.target = (window.USE_SAME_WINDOW) ? "" : '_blank';
			});
}

if (window.manager)
manager.types.hitta = {
	init_widget: hitta_init_widget
};
;/* styles/base/js/hitta.js */
function weather_init_widget(widget, force)
{
    weather_resize_widget(widget);

    $('.city strong', widget.dom).hover(function() {
                this.style.textDecoration = 'underline';
            },
            function() {
                this.style.textDecoration = 'none';
            }).editable(function(value) {
                widget.element.addClass('loading');
                $.ajax({
                    url: resolve_url(widget.dom, 'settings/'),
                    type: 'post',
                    data: { location_name: value },
                    success: function(data) {
                        set_content(widget.element, data);
                        weather_resize_widget(widget);
                        widget.element.removeClass('loading');
                    }
                });
                return value;
            },
            {
                submit: 'spara',
                width: 100
            });
}

function weather_resize_widget(widget) /* used to center floated tables */
{
    var container = $('div.temperatures', widget.dom).css('width', 'auto');
    var tables = $('> table', container);
    if (tables.length < 1) return;

    var max_right = 0;
    tables.each(function() {
            var t = $(this);
            max_right = Math.max(max_right, t.offset().left + t.width());
        });

    var w = max_right - $(tables[0]).offset().left;
    if (w > 1) container.css('width', w + tables.length * 2);
}

if (window.manager)
manager.types.weather = {
    init_widget: weather_init_widget,
    resize: weather_resize_widget
}
;/* styles/base/js/weather.js */
// vim: set ai ts=4 sts=4 et sw=4

var COLUMN_SELECTOR = '#widgetcontainer > div.column';
var WIDGET_SELECTOR = '> div.widget:not(.dummy):not(.ui-sortable-helper)';
var WIDGET_WIDTH = 100;
var CURRENT_AUDIO = false;

function get_widget(child)
{
    if (child.jquery)
        if (child.length)
            child = child[0];
        else return null;

    while (child.parentNode)
    {
        var c = $(child);
        if (c.is('div.dialog, div.widget'))
            return c;
        child = child.parentNode;
    }
    return [];
}

function update_modified(data)
{
    return;
    var timestamp = data.match(/^(\d+)/);
    if (!timestamp)
        return;

    var current_modified = data.match(/ (\d+)/);
    if (current_modified)
    {
        var current_modified = parseInt(current_modified[1], 10);
        if (window.LAST_MODIFIED && window.LAST_MODIFIED < current_modified)
            location.reload();
    }

    var new_modified = parseInt(timestamp[1], 10);
    window.LAST_MODIFIED = Math.max(window.LAST_MODIFIED, new_modified);
}

function set_content(widget, data)
{
    widget = $(widget);
    var target = $('div.content', widget);
    if (!target.length)
        target = widget;

    var old_height = target.height();
    target.height(old_height);
    target.html(data);
    target.height('auto');

    var transparent = widget.css('backgroundColor') == "transparent";
    if (!widget.is('.shaded') && !transparent)
        target.effect('highlight', {}, 500);

    widget.removeClass('loading');

    Actions.apply(widget);

    manager.init_widget(widget);

    if (widget.parents('#lightbox').length && !manager.find(widget)) // Re-center
    {
        if (Math.abs(old_height - target.height()) > 30)
            lightbox(widget);
    }
}

function handle_toolbar(widget)
{
    var titlediv = $('> div.title', widget);

    if ($.browser.msie) // IE Bug, selects text on drag
        $('> h2', titlediv).bind('selectstart', function(a) { return false; });

    titlediv.dblclick(function() { $('> div.toolbar a.shade', this).each(Actions.linkclick); return false; });

    $('> div.toolbar img', titlediv).hover(
        function() {
            this.src = this.src.replace('.gif', '-hover.gif');
        }, 
        function() {
            this.src = this.src.replace('-hover.gif', '.gif');
        }
    );

    init_editables(widget);

    $('> div.title *[title]', widget).cluetip({ 
        cursor: '', 
        splitTitle: ' - ', 
        positionBy: $.browser.msie ? 'auto' : 'mouse', 
        tracking: !$.browser.msie
    });
}

function resolve_url(widget, url, skipsuffix, suffix)
{
    if (!url)
        url = '';

    url = url.replace(/^(https?:..)[^\/^@]+@/, '$1'); // remove auth
    var hostinfo = window.location.protocol + '//' + window.location.host;

    if (url.substring(0, hostinfo.length) == hostinfo)
    {
        url = url.substring(hostinfo.length);
    }

    var p = manager.find(widget);
    if (p)
    {
        var re = /^\/w\/(\w+)\/(-?\d+)(\/\d+\/\d+)?/;
        if (url.match(re))
            url = url.replace(re, '/w/$1/$2/' + p.col + '/' + p.index);
        else
        {
            var parts;
            if (url.charAt(0) != '/')
                parts = [ 'w', p.type, p.id || 0, p.col, p.index, url ]
            else
                parts = [ p.id || 0, p.col, p.index, url.substring(1) ];

            url = '/' + parts.join('/');
        }
    }
    if (!skipsuffix)
    {
        if (!suffix) suffix = 'reload';
        var i = url.indexOf('?');
        if (i != -1)
            url = url.substring(0, i) + suffix + '/' + url.substring(i);
        else 
            url += suffix + '/';
    }
    return url;

}

var Actions = new Object({

    init: function() {
        Actions.actions = {
            add_dialog: Actions.add_dialog,
            close_add_dialog: Actions.close_add_dialog,
            reloadinner: Actions.reload_inner,
            replace: Actions.replace_widget,
            dialog: Actions.open_dialog,
            add: Actions.add_widget,
            popup: Actions.popup,
            settings: Actions.settings_menu,
            shade: Actions.shade,
            remove: Actions.remove,
            tab: Actions.open_tab,
            audio: Actions.play_audio,
            trigger_event: Actions.trigger_event
        }
    },

    apply: function()
    {
        if (window.applied) return; window.applied = true;

        var linkevent = function(fn, require_button)
        {

            var wrap = function(ev)
            {
                /* check for middleclick (require_button == 1) */
                if (require_button && (!ev.button || ev.button != require_button))
                    return;

                var target = ev.target;
                do {
                    if (target.tagName == "A")
                        return fn.apply(target, wrap.arguments);
                } while (target && (target = target.parentNode))
            }
            return wrap;
        }
        $(document.body).click(linkevent(Actions.linkclick)).mousedown(linkevent(Actions.linkclick, 1));
    },

    linkclick: function()
    {
        var a = $(this);

        var rels = a[0].rel.split(/[ \n]+/);
        var rel = [];

        for (var i = 0; i < rels.length; i++)
        {
            if (rels[i].charAt(0) == '#')
                rel._target = rels[i];
            else if (rels[i].length)
                rel.push(rels[i]);
        }

        var ret = true;

        for (var i = 0; i < rel.length; i++)
        {
            var fn = Actions.actions[rel[i]];
            if (fn && fn.call(this, rel._target) === false)
                ret = false;
        }
        
        if (!ret)
            return false;

        /* External link */
        if (this.href.indexOf("http") == 0 && this.href.indexOf(window.location.host) == -1)
        {

            var domain = this.href.match(/\/\/(www\.)?([^\/]+)/)[2];

            if (window.pageTracker)
                pageTracker._trackPageview('/out/' + domain);

            this.target = (window.USE_SAME_WINDOW) ? "" : '_blank'; 

            if (!this.origHref)
            {
                this.origHref = this.href;
                this.href = '/out/?redirect=1&url=' + escape(this.href);
                setTimeout(function() {
                        a[0].href = a[0].origHref;
                        a[0].origHref = null;
                        }, 700);
            }
            return ret;
        }

        /* Scroll within page */
        var hashindex = this.href.indexOf('#');
        var hash = (hashindex != -1) ? this.href.substring(hashindex) : '#';
        if (hash != '#' && this.href.indexOf(window.location.href.replace(/#.*/, "")) == 0)
        {
            $.scrollTo($(hash), 400);
            return false;
        }

        return ret;
    },

    reload_inner: function(url)
    {
        var widget = get_widget(this);
        widget.addClass('loading');

        $.ajax({
            url: resolve_url(widget, url || this.href),
            success: function(data) {
                set_content(widget, data);
            },
            error: function(req) {
                widget_error(widget, req);
            }
        });

        return false;
    },

    add_dialog: function()
    {
        var addbar = $('#add-bar');
        addbar.hide();
        $('#main-content').hide();
    var addcontainer = $('#addcontainer');
    if (addcontainer.height() < 100)
        addcontainer.height('50%')
    addcontainer.show();
    },

    close_add_dialog: function()
    {
    if ($('#add-bar:visible').length)
        return true;

        $.history.add('');

        $('div.add:visible').remove();
        $('#addcontainer').slideUp(function() { $('#add_dialog').remove() });
        $('#add-bar').slideDown();
        $('#main-content').show();
        return false;
    },

    replace_widget: function() 
    {
        if (window.DUMMY) return dummy();

        var widget = get_widget(this);
        widget.addClass('loading');

        $.ajax({
        url: resolve_url(widget, this.href, true),
        success: function(data) {
            var div = $(data);
            manager.new_widget(div);

            manager.remove_widget(widget);
            }
        });
        return false;
    },

    popup: function()
    {
        window.open(this.href, 'popup', 'width=' + Math.min($(window).width(), 1024) + ', height=' + Math.min($(window).height(), 768) + ', toolbar=0, menubar=0, scrollbars=1');
        return false;
    },

    open_dialog: function(target, skip_history) 
    {
        var widget = get_widget(this);
        var url;
        if (widget.length)
        {
            widget.addClass('loading');
            url = resolve_url(widget, this.href, false, 'dialog');
        }
        else
        {
            $(this).addClass('loading');
            url = this.href.replace('%3F', '?').replace(/(\?|$)/, 'dialog/?no_layout=1&').replace(/[?&]+$/, '');
        }

    var new_hash = url.replace(/^[^?]+\/\/[^\/]+/, '').replace(/dialog\/($|\?)/, '$1').replace('?', '%3F');
    if (!skip_history) $.history.add(new_hash);

        var link = this;

        if (target)
    {
        target = $(target);
        if (!target.length)
            target = widget.length ? widget : null;
    }

    if (target)
                target.addClass('loading');

    var self = this;
        $.ajax({
            url: url,
            success: function(data) {
                $(widget.length ? widget : self).removeClass('loading');
                if (data.match(/<html/i))
                {
                    widget_error(link);
                    return;
                }
            
        var div;
                if (target)
                {
            div = target;
                    target.html(data);
                    target.slideDown(function() { 
                target.height('auto');
            });
                    $.scrollTo(target, 400, { over: -0.5 });
                    target.removeClass('loading');
                }
                else
                {
            div = $(data);
            if (!div.is('div.widget'))
            {
                    $(document.body).prepend(div);
                    lightbox(div);
            }
                }

                if (!target && div.is('div.widget'))
                {
                    handle_new_widget(div);
                }
                else
                {
                    Actions.apply(div);
                    handle_toolbar(div);
                }

                $('input:first', div).focus();

                $(target || '#widgetcontainer').trigger('dialog_loaded');
            }
        });
        return false;
    },

    shade: function() 
    {
        if (window.DUMMY) return dummy();

        var l = this;
        if (l.working)
            return false;
        l.working = true;

        var widget = get_widget(this);

        widget.addClass('loading');
        widget.toggleClass('shaded');

	var img = $('img', this)[0];
        if (widget.is('.shaded'))
            img.src = img.src.replace(/minimize(-hover)?.gif/, 'maximize$1.gif');
        else
            img.src = img.src.replace(/maximize(-hover)?.gif/, 'minimize$1.gif');

        var url = resolve_url(widget, 'shade/?ajax', true);
        $.ajax({
            url: url,
            type: 'post',
        data: { '_': 1 },
            success: function(data) { 
                l.working = false;
                widget.removeClass('loading');

                update_modified(data);
            },
            error: function(req) {
                l.working = false;
                widget_error(widget, req);
                widget.toggleClass('shaded');
            }
        });

        return false;
    }, 

    remove: function()
    {
        var l = this;
        if (l.working)
            return false;
        l.working = true;

        lightbox_close();
        var widget = get_widget(this);
        if (!manager.find(widget[0]))
        {
            widget.remove()
            $.history.add('');
            return false;
        }
        if (window.DUMMY) return dummy();
        widget.addClass('loading');

        var url = resolve_url(widget, this.href, true);
        $.ajax({
            url: url,
            type: 'post',
        data: { '_': 1 },
            success: function(data) {
                l.working = false;
                manager.remove_widget(widget);
                widget.removeClass('loading');

                update_modified(data);
            },
            error: function(req) {
                l.working = false;
                widget_error(widget, req);
            }
        });

        return false;
    },

    add_widget: function() 
    {
        if (window.DUMMY) return dummy();
        window.LAST_MODIFIED = 0;

        var widget = get_widget(this);

        widget.addClass('loading');

        var url = this.href;
        url += (url.indexOf('?') == -1 ? '?' : '&') + 'no_layout=1';

        $.ajax({
            url: url, 
            success: function(data) {

                var tmp = document.createElement('DIV');
                tmp.innerHTML = data;
                handle_new_widget($(tmp).children());
                widget.removeClass('loading');

            },
            error: function(req) {
                widget_error(widget, req);
            }
        });
        $('div.notification.info').show();

        return false;
    },

    settings_menu: function()
    {
        var widget = get_widget(this);

        widget.addClass('loading');

        var info = manager.find(widget);

        var has_settings = true;

        try {
            has_settings = (manager.types[info.type].settings == undefined || manager.types[info.type].settings);
        } catch (e) {}

        var link = this;

        function settings_menu_display(items, values, action)
        {

            widget.removeClass('loading');

            function postSettings(key, value) {
                if (window.DUMMY) return dummy();

                values[key] = value;

                widget.addClass('loading');
                $.post(resolve_url(widget, action), values, function(data) {

                    set_content(widget, data);

                    menu.remove();
                });
            }

            var menu = $('<ul class="popup settings-menu" />');
            menu.hover(function(){
                    clearTimeout(menu.hideTimer);
                }, function() { 
                    clearTimeout(menu.hideTimer);
                    menu.hideTimer = setTimeout(function() {
                    menu.remove(); 
                    }, 600);
                }
            );

             $(link).hover(function() {},
             function() {
                     menu.hideTimer = setTimeout(function() {
                        menu.remove(); 
                    }, 600);
             });

            // Default

            var item = $('<li>Byt namn</li>');
            item.click(function() { 
                var target = $('div.title h2 span:not(.override)', widget);
                target.click(); 
            });

            menu.append(item);

            var has_extra = false;
            try {
            has_extra = (manager.types[info.type].settings_items);
            } catch (e) {}

            if (has_extra)
            {
                if ($.isFunction(has_extra))
                    has_extra = has_extra(widget, menu);
                menu.append(has_extra);
                Actions.apply(has_extra);
            }

            var widget_link = $('div.title h2 a', widget);
            if (widget_link.length)
            {
                var domain = widget_link[0].href.match(/([^\.^\/]+\.[a-z]+)(\/|$)/)[1];
                item = $('<li>Gå till <a href="' + widget_link[0].href + '">' + domain + '</a></li>');
        Actions.apply(item);
                item.click(function() {  
                    var a = $('a', this);
                    if (a.click()) window.open(a[0].href);
                });
                menu.append(item);
            }

            if (!items)
                items = [];

            $(items).each(function() {
                var itemdata = this;
                var item = $('<li>' + itemdata[0] + '</li>');
                $(menu).append(item);

                if (typeof this[2] == 'object') // select
                {
                    item.addClass("parent");
                    var sub = $('<ul />');
                    sub.css({ display: 'none' });
                    $(this[2]).each(function() {
                        var subdata = this;
                        var subitem = $('<li>' + subdata[0] + '</li>');
                        if (!subdata[2] && (values[itemdata[1]] == subdata[1]))
                        {
                            var check = $('<input type="checkbox" name="' + itemdata[1] + '" />');
                            subitem.append(check);
                        }

                        if (subdata[2]) // disabled
                            subitem.addClass('disabled');
                        else
                            subitem.click(function() { postSettings(itemdata[1], subdata[1]); });
                        sub.append(subitem);
                    });
                    item.append(sub);

                    var fn_show_subs = function() { 
                        clearTimeout(item.hideTimer);

                        $(this).siblings().children('ul').hide();

                        var pos = get_position(this, sub, 200);
                        sub.css({ left: pos.left - pos.cleft, width: pos.width }).show(); 
                    }
                    item.hover(fn_show_subs, function() { 
                        clearTimeout(item.hideTimer);
                        item.hideTimer = setTimeout(function() {
                            $('> ul', item).hide(); 
                        }, 600);
                    } );
                }
                else if (typeof itemdata[2] == 'boolean')
                {
                    var check = $('<input type="checkbox" name="' + itemdata[1] + '" />');
                    item.append(check);
                    item.click(function() { postSettings(itemdata[1], itemdata[2] ? '' : "on"); });
                }
                else
                {
                    item.click(function() {
                            var changed = false;

                            $(items).each(function() {
                                if (typeof this[2] != 'string') return;

                                var value = prompt(this[0], this[2]);
                                if (value != this[2] && value != null)
                                {
                                    changed = [ this[1], value ];
                                    values[this[1]] = value;
                                }
                            });
                            if (changed)
                                postSettings.apply(this, changed);
                    });
                }
            });
            $(document.body).append(menu);

            if ($.browser.msie)
                $('li', menu).hover(
                    function() { 
                        $(this).addClass('hover'); 
                    }, 
                    function() { 
                        $(this).removeClass('hover'); 
                    }
                );

            menu.css('position', 'absolute');
            var pos = get_position(link, menu, 200);
            menu.css({
                left: pos.left,
                width: pos.width,
                top: pos.top,
                zIndex: 99
            });
            menu.show();

            $('input[type=checkbox]', menu).each(function() {
                this.checked = values[this.name];
            });

        }

        if (has_settings) // Fetch settings form and extract values
        $.ajax({
            url: resolve_url(widget, this.href), 
            success: function(data) {

                var div = $(data);
                var form = (div.length > 1) ? div.filter('form') : (div.is('form') ? div : $('form', div));

                var labels = $('label', form);

                var items = [];
                var values = {};

                labels.each(function() {
                    var label = this;

                  $('#' + this.htmlFor, form).each(function() {
                    var title = $(label).text() || this.name;

                    if (this.type == "submit")
                        return null;
                    
                    values[this.name] = $(this).val();

                    var value;
                    if (this.tagName == "SELECT")
                    {
                        value = [];
                        $('option', this).each(function() {
                            value.push([ $(this).text(), this.value || this.innerHTML, this.disabled || $(this).is('.disabled') ]);
                        });
                    }
                    else if (this.type == "checkbox" || this.type == "radio")
                    {
                        value = this.checked;
                        values[this.name] = this.checked ? 'true': '';
                    }
                    else
                        value = this.value;

                    items.push([ title, this.name, value ]);
                  });
                });
                
                $('input[type=hidden]', form).each(function() { 
                    values[this.name] = this.value;
                });

                if (form.length)
                    settings_menu_display(items, values, form && form[0].action);
                else
                    settings_menu_display();
            },
            error: function() {
                settings_menu_display();
            }
        });

        return false;
    },    

    open_tab: function() 
    {
        var self = this;

        var tabs = $('#tabs > li');
        var current = tabs.filter('.open');
        var current_index = tabs.index(current);
        var new_tab_index = $(this).parents('li').data('index');

        if (current_index == new_tab_index)
        {
            return false;
        }
    else if (!window.LOAD_TAB && current.length) // Set initial tab for back navigation
    {
        if (current_index != new_tab_index)
            $.history.add('/tab/' + current_index + '/');
    }
    $.history.add('/tab/' + new_tab_index + '/');

        var wcontainer = $('#widgetcontainer');
        $(self).addClass('loading');
        wcontainer.addClass('loading');

    current.removeClass('open');
    $(tabs[new_tab_index]).addClass('open');

    current.children('a')[0].editing = true;

        $.ajax({
            url: '/tab/set/' + new_tab_index + '/reload/',
            success: function(data) {
                $('#cluetip').hide();

                wcontainer.removeClass('loading');
                $(self).blur().removeClass('loading');
                self.editing = false;

                $('#widgetcontent').html(data);

        window.LOAD_TAB = true;

                manager.clear_widgets();
                initialized = false;
                init_all();
            }
        });
        return false;
    },

    play_audio: function() 
    {
        var containerID = "mediaplayer";

        var track = function(url) {
            $.ajax({
                url: '/out/',
                data: { url: url },
                error: function(){}
            });
        }

        if (!CURRENT_AUDIO)
        {
            AudioPlayer.setup("/static/js/lib/audio-player/player.swf", {  
                width: 200,  
                initialvolume: 100,  
                transparentpagebg: "yes",  
                autostart: "yes",
                animation: "no"
            });  

            AudioPlayer.embed(containerID, { soundFile: this.href, titles: this.title });
            CURRENT_AUDIO = this.href;
            track(this.href);
            return false;
        }

        if (CURRENT_AUDIO == this.href)
        {
            AudioPlayer.close(containerID)
            CURRENT_AUDIO = true;
        }
        else
        {
            AudioPlayer.load(containerID, this.href, this.title);
            AudioPlayer.open(containerID);
            CURRENT_AUDIO = this.href;
            track(this.href);
        }

	return false;
    }


});
Actions.init();

var tempShaded = false;
function tempShade()
{
	if (!tempShaded)
		$(COLUMN_SELECTOR + WIDGET_SELECTOR).addClass('shaded');
	else
	{
		var shaded = [ [], [] ]; // 0: not shaded, 1: shaded

		$(manager.widgets).each(function() {
			shaded[this.shaded ? 1 : 0].push(this.dom);
		});
		$(shaded[0]).removeClass('shaded');
		$(shaded[1]).addClass('shaded');
	}
	tempShaded = !tempShaded;
}

function handle_new_widget(widget)
{
        Actions.close_add_dialog();

        if (!widget.jquery)
            widget = $(widget);

        manager.new_widget(widget);
        lightbox(widget, widget.parent());

}

function get_position(caller, element, max_width, center)
{
    if (!max_width)
        max_width = 500;

    var old_position = $(element).css('position');
    $(element).css('position', $.browser.msie ? 'absolute' : 'relative');

    var c_offset = $(caller).offset({ border: true });
    var caller_left = c_offset.left;
    var caller_top = c_offset.top;
    var caller_width = $(caller).width();
    var element_width = $(element).width();
    var element_height = $(element).height();

    $(element).css('position', old_position);

    var window_width = $(window).width();
    var window_height = $(window).height();

    var width = Math.min(window_width, element_width, max_width);
    if (!($.browser.msie && $.browser.version < 7))
        if (element_width / max_width < 2)
            width = Math.min(window_width, element_width);

    var left = (caller_left + caller_width + width > window_width)
        ? left = caller_left - width
        : caller_left + caller_width;

    var right = window_width - (caller_left + caller_width);

    if (center)
    {
            left = (window_width - width) / 2;
            right = left;
    }

    var top = $(caller).offset().top;
    if (top + element_height > window_height)
    {
        top = Math.max(0, top - element_height);
    }

    if (center)
            top = (window_height - element_height) / 2 + (window.pageYOffset ? window.pageYOffset : document.body.scrollTop);

    return { 
            left: Math.max(0, Math.floor(left)), 
            width: Math.floor(width), 
            height: element_height,
            top: Math.max(0, Math.floor(top)), 
            right: Math.max(0, Math.floor(right)), 
            ctop: Math.floor(caller_top),
            cleft: Math.floor(caller_left)
    };
}

function lightbox(widget, parent) {

    if (!widget || (widget.jquery && !widget.length))
        return lightbox_close();

    $('#lightbox').remove();

    var lb = $('<div id="lightbox" />');
    var bg = $('#lightbox-bg');
    if (!bg.length)
    {
        bg = $('<div id="lightbox-bg" />');
        $(document.body).append(bg);
    }

    $(parent ? parent : document.body).prepend(lb);

    var shadow = $('<div class="lightbox-shadow" />');
    shadow.css('position', 'absolute');
    shadow.append(widget);
    lb.append(shadow);

    bg.css({
        position: 'absolute',
        top: 0,
        left: 0,
        width: $(document).width(),
        height: $(document).height(),
        opacity: 0.5,
        zIndex: 9
    });

    widget.css({
        position: 'relative',
        zIndex: 90
    });

    if ($.browser.msie && $.browser.version < 7)
    {
        $('select').css('visibility', 'hidden');
        $('#lightbox select').css('visibility', 'visible');
    }

    $('object').css('visibility', 'hidden');
    $('#lightbox object').css('visibility', 'visible');

    var IE6 = ($.browser.msie && $.browser.version < 7);
    var pos = get_position(lb, widget, 600, true);

    pos.width += 5;
    shadow.css({ 
        width: pos.width,
        zIndex: 90,
        margin: 0
    });

    if (!parent) 
    {
        shadow.css({
        position: 'absolute',
        left: Math.max(($(window).width() - pos.width) / 2, 0),
        top: Math.max(($(window).height() - pos.height) / 2, 0)
        });
    }

    var shadows = $([]);
    var z = 90 - 6;
    var h = IE6 ? shadow.height() : '100%';
    for (var i = 0; i < 6; i++)
    {
            shadows = shadows.add($('<div class="shadow"></div>').css({ 
                    position: "absolute",
                    backgroundColor: '#000',
                    zIndex: z + i, 
                    opacity: .1, 
                    top: i + 1, 
                    left: i + 1, 
                    width: pos.width,
                    height: h
                }));
    }
    shadow.prepend($(shadows));

    if (manager.find(widget)) // Display "drag me"-tooltip for widgets
    {
        widget.width(window.WIDGET_WIDTH);
        var title = $('> div.title', widget);

        var cluetip = $('> h2', title).data('cluetip');
        if (cluetip)
        {
            var pos = widget.offset();
            cluetip({ pageX: pos.left + Math.floor(widget.width() - 20), pageY: pos.top });
        }

        if (title.css('backgroundColor') != 'transparent')
        for (var i = 0; i < 15; i++)
        {
            title.effect("highlight", {}, 2000);
        }
    }
}

function lightbox_close()
{
    $('#lightbox').remove();
    $('#lightbox-bg').remove();
    $('#cluetip').hide();
    if ($.browser.msie && $.browser.version < 7)
    {
        $('select').css('visibility', 'visible');
    }
    $('object').css('visibility', 'visible');
}

function check_dummys()
{
    var max_h = 0;
    $(COLUMN_SELECTOR).css('minHeight', 'auto').each(function(col) {
        if (!$(WIDGET_SELECTOR, this).length)
    {
        if (!$('div.widget.dummy', this).length)
            $(this).append('<div class="widget dummy"><div class="title"><h2>&nbsp;</h2></div></div>');
    }
    else
    $('div.widget.dummy', this).remove();

    var h = $(this).height();
    if (h > max_h)
    max_h = h;
    }).css('minHeight', max_h);
}

function init_tabs()
{
    $('#tabs').sortable({
        items: 'li',
        axis: 'x',
        containment: 'parent',
        distance: 5,
        placeholder: 'droptarget',
        update: function(ev, ui)
        {
            var tabs = $('#tabs > li:not(.sortable-helper)');
            var old_index = ui.item.data('index');
            var new_index = tabs.index(ui.item);
            var url = '/tab/move/' + old_index + '/' + new_index + '/';
            $.ajax({
                url: url,
                type: 'post',
		data: { '_': 1 },
                success: function() {
                    ui.item.data('index', new_index);
                },
                error: function(req) {
                    if (old_index == 0)
                        $(tabs[0]).before(ui.item);
                    else
                        $(tabs[old_index - 1]).after(ui.item);

                    widget_error(ui.item, req);
                }
            });
        }
    }).children().each(
        function(index) {
            $(this).data('index', index);
        }).mousedown(function() {
            $(this).data('index', $('#tabs > li').index(this));
        }).children('a').each(
            function() {
                if (!$(this).parent().is('.open'))
                    this.editing = true; // Disable editable for inactive tabs
            }).editable('/set_title/', {
                submitdata: function() {
                    return { 
                        tab_index: $('#tabs > li').index(this.parentNode) 
                    };
                }
            });
}

function init_top_addfeed()
{ 
    $('#top_new_feed').focus(function() {
            if (this.value == this.title) this.value='';
            this.className = '';
        }).blur(function() {
            if (this.value == '') {
                this.value = this.title;
                this.className = 'blur';
            }
        }).blur();
    
    $('#add-feed-top form').submit(function() {
            var t = $('input:text', this).focus();
            if (!t.val())
            {
                return false;
            }
            this.href = this.action + '?' + $(this).serialize(); /* for open_dialog */
            Actions.open_dialog.call(this, null, true);
            $('#widgetcontainer').bind('dialog_loaded', function() {
                    t.val('').blur();
                });
            return false;
            });
}

function init_editables(target)
{
    $('div.title > h2 > span:not(.override)', target).editable(
            function(value) {

            value = $.trim(value);
            if (!value || (value == this.origText) || (value == this.curText)) 
            return (value || this.origText);

            $.ajax({
url: '/set_title' + resolve_url(get_widget(this), '/', true),
type: 'post',
data: { value: value }
});

            return this.curText = value;
            },
            {
style: 'inherit',
onblur: 'submit',
width: '50%',
data: function(html) {
    return $('<div />').html(html).text();
}

}).attr('title', 'Byt namn - Klicka här för att ändra titeln för det här innehållet');
}

function init_all()
{
    if (initialized)
        return;
    initialized = true;

    var widgetcontainer = $('#widgetcontainer');

    widgetcontainer.addClass('initializing');

    var hash = window.location.hash;
    if (hash.charAt(0) == '#') hash = hash.substring(1);
    if (hash == 'reload')
    {
        window.location.hash = '#';
        window.location.href = '/';
        setTimeout(init_all, 500);
    }

    var columns = widgetcontainer.children('div.column');

    function update_widget_width() 
    {
        var total_width = widgetcontainer.width();
        var column_count = columns.length;
        WIDGET_WIDTH = Math.floor(total_width / column_count);

        if ($.browser.msie && $.browser.version < 7)
            WIDGET_WIDTH -= 40;
    }
    update_widget_width();
    $(window).resize(update_widget_width);

    manager.init_types();
    manager.init_widgets();

    $('#add a').unbind('click').click(function() { $.scrollTo('#add-bar', 200); return false; });

    init_tabs();

    if (window.LOAD_TAB)
    {
        Actions.apply('#widgetcontainer', true);
    }
    else
    {
        $(function() { 
                $(window).history(history_callback);
                history_callback(null, $.history.getCurrent());
                })
        init_top_addfeed();

        Actions.apply(document.body, true);
	$(window).keydown(function(ev) {
		if (ev.keyCode == 27) // Escape
			$('ul.popup').remove();
	});
    }
    $(function() { setTimeout(init_deferred, window.LOAD_TAB ? 0 : 50); });

    if ($.browser.msie) // Set page as homepage
    {
	    $('a#default-homepage').click(function() {
		    this.setHomePage('http://starta.nu/');
		    if (window.pageTracker)
			    pageTracker._trackPageview('/set_homepage/'); 
		    return false;
	    }).attr('rel', '').attr('href', '#');
    }
    else if ($.browser.safari) // Hide for now
    {
	    var link = $('a#default-homepage');
	    $(link.parent().children('span').slice(-1)).remove()
	    link.remove();
    }
}

function init_deferred()
{
    handle_toolbar(COLUMN_SELECTOR + WIDGET_SELECTOR);

    var widgetcontainer = $('#widgetcontainer');
    check_dummys();

    var columns = widgetcontainer.children('div.column');

    if (columns.is('.ui-sortable'))
        columns.sortable('refresh');
    else if (navigator.userAgent.toLowerCase().indexOf('iphone') == -1)
      columns.sortable({
        items: '> div.widget',
        handle: '> div.title > h2',
        connectWith: [ columns ],
        placeholder: 'droptarget',
        opacity: 0.6,
        delay: 100,
        dropOnEmpty: false,
        scroll: true,
    tolerance: 'intersect',

        start: function(ev, ui) {
            ui.item.css({ position: 'static' });
            ui.item.removeClass('new');
            ui.helper.width(window.WIDGET_WIDTH);
            ui.item.width(window.WIDGET_WIDTH);
            $('div.title', ui.item).queue([]);
            ev.preventDefault();

        $('#lightbox > lightbox-bg, #lightbox div.shadow, #cluetip').css('display', 'none');
            return false;
        },
        stop: function(ev, ui)
        {
            setTimeout(function() {
                    var w_options = manager.find(ui.item[0]);
                    var new_p = w_options.placement(true);
                    w_options.move(new_p.id, new_p.col, new_p.index);
            }, 400);
            ui.item.width('auto');

            $('div.notification.info').show();
            lightbox_close();
        }
    });

    if (window.highlight)
    {
        var wh = window.highlight;
        try {
            var w = manager.find(wh[0], wh[1]).element;
            if (w)
                lightbox(w, w.parent());
        } catch (e) { }
    }

    if ($.browser.msie)
        columns.css('position', 'static'); // IE z-index bug

    widgetcontainer.removeClass('initializing');
}

function history_callback(ev, hash)
{
    var m;
    if (m = hash.match(/^\/tab\/(\d+)\/$/)) // Tab
    {
        lightbox_close();
        Actions.open_tab.call($('#tabs li:eq(' + m[1] + ') a')[0]);
    }
    else if (hash.charAt(0) == '/') // reopen dialogs
    {
        if ($('#widgetcontainer').is('.initializing'))
            lightbox($('<div id="splash" class="dialog"><div class="content">Laddar...</div></div>'));

        var target = '';
        if ((hash.indexOf('/add/') != -1) && (hash.indexOf('/tab/') == -1))
        {
            lightbox_close();
            target = '#addcontainer';
            Actions.add_dialog();
        }
        Actions.open_dialog.call({ href: hash }, target, true);
    }
    else if (hash == '#' || hash == '')
    {
        lightbox_close();
        if ($('#addcontainer > div').length)
        {
            Actions.close_add_dialog();
        }
    }
}


function handle(form, skipsuffix)
{
    if (window.DUMMY)
        return !dummy();

    form = form || this;
    var data = $('input, textarea, select', form).serialize();
    var widget = get_widget(form);

    if (!widget || !widget.length)
            return false;

    widget.addClass('loading');

    var url = form.action;
    url += (url.indexOf('?') == -1 ? '?' : '&') + 'no_layout=1';

    $.ajax({
        url: resolve_url(widget, url, skipsuffix), // TODO no_layout query
        data: data,
        type: 'POST',
        success: function(data) { 

            if (data.toLowerCase().indexOf('<html') != -1)
            {
                data = data.replace(/[\r\n]/g, ' ').replace(/.*<body.*?>(.*)<\/body>.*/i, '$1');
            }

            var div = $(data);

            if (div.is('div.widget'))
            {
                handle_new_widget(div);

                $.get(this.url, function(data) {
                    set_content(widget, data);
                });
            }
            else
            {
                set_content(widget, data);
            }
        }
    });

    return true;
}

function dummy()
{
    alert('Ändringar har avaktiverats eftersom du använder en annan användares innehåll.'); 
    return false;
}

var cur_col = 0;
var widgets = [ ]

function widget_error(widget, request)
{
    var dest = $('.title h2', widget);
    if (!dest.length)
        dest = $(widget);
    dest.effect("highlight", { color: '#ff0000'}, 1000);

    check_ajax_error(request);
}

function check_ajax_error(request)
{
    if (window.DUMMY) return dummy();

    if (!request)
           return;

    if (request.status == 400) // Not sync'ed between screen and server
    {
        var e = $('<div class="widget dialog"><div class="content"><h2>Synkroniseringsfel!</h2>Felet beror mest troligt på att ditt innehåll har ändrats<br />från en annan webbläsare eller dator sedan du senast laddade din sida.<p><strong><a href="/">Ladda om sidan</a></strong> för att hämta den senste versionen och försök igen!</p></div></div>');
        lightbox(e);
    }
}

$(function() {

$.ajaxSetup({
        error: function(request) {
        if (window.DUMMY)
            return dummy();

        if ($('#lightbox div.splash'))
            lightbox_close();

        $(document.body).effect("highlight", { color: '#ff0000'}, 1000);

    check_ajax_error(request);
    },
    cache: false
});

});

var initialized = false;
$(init_all);

$(function() {
    if (window.pageTracker)
        $(window).ajaxSuccess(function(ev, req, settings) {

            if ($('#widgetcontainer').is('.initializing'))
                return;

            var url = settings.url;
            url = url.replace(/^(\/w\/[^\/]+\/)-?\d+\/\d+\/\d+\/(.*)/, '$1$2'); // id and placement
            url = url.replace(/([&?])_=\d+(&|$)/, '$1').replace(/&$/, ''); // unique request id

            if (url.match(/^\/check_modified\//))
                return;

            pageTracker._trackPageview(url);
        });
});
;/* styles/base/js/john.js */
setInterval(function() {
	$.getJSON('/help/tips/json/', function(help_texts) {
        cycle_tips(container, help_texts);
	});
}, 15 * 60000);

function cycle_tips(container, help_texts)
{
	container = $(container);
    if (!container.length || !help_texts.length) return;
    if ($(window).width() <= 800)
	    return;

	var target = $('span', container);

	var i = -1;
	function shift()
	{
		if (this.disabled) return false;

        $('a.more', container).animate({opacity: 0}, 'fast')
		target.animate({ opacity: 0 }, function() { 
			var cur = help_texts[i];

			var content = cur[0];
			if (cur[1]) // url
                $('a.more', container).css('display', 'inline').animate({opacity: 1}).attr('href', cur[1]);

			target.html(cur[0]); 
            if (cur[2])
                target.attr('title', cur[2]);
		}).animate({ opacity: 1});

		i = (i < help_texts.length - 1) ? i + 1 : 0;

		return false;
	}
	shift();

    if (container.data('timer')) 
        clearInterval(container.data('timer'));
    else // already initialized
    {
        target.hover(function() { this.disabled = true; }, function() { this.disabled = false; });
    }

	container.data('timer', setInterval(shift, 10000));

}
;/* styles/base/js/help.js */
function style_init_grid()
{
    var custom_styles = $('div.custom-styles > div:gt(2), div.custom-styles p.pagenav').hide();
    if (custom_styles.length > 1)
    {
        $('<p class="pagenav"><a href="javascript:void(0)">visa fler</a></p>').insertBefore(custom_styles[0]).click(function() {
                $(this).remove();
                custom_styles.show();
                return false;
                });
    }
}

function style_init_bg_grid()
{
    function bg_toggle()
    {
        function toggle(target, show)
        {
            if (show) target.show();
            else target.hide();

	    return show;
	}

        toggle($('#opacity_form'), $('#use_bg').is(':checked') || $('#use_style_bg').is(':checked'));

        if (toggle($('#background_choices'), $('#use_bg').is(':checked'))) // Enable bg-image 
	{
		toggle($('#background_choices > div.images'), !$('#background_choices').is('.new_image'));

		if (toggle($('#custom_bg_form'), $('#custom_bg').is(':checked')))
		{
			toggle($('#id_color, #id_position').parents('tr'), 
					$('#id_repeat option[selected]').val() != 'repeat');
		}
	}
    }

    var inputs = $('input, select', '#styles')
    function preview_bg(ev)
    {
        bg_toggle();
        if (inputs.wait) return;
        inputs.wait = true;

        $.ajax({
            url: '/style/css/background/',
            type: 'post',
            data: inputs.serialize(),
            success: function(data) {
            inputs.wait = false;
                    var target = $('#style-bg-css');
		    if ($.browser.msie && $.browser.version < 7)
		    {
		    	target.remove(); // IE6 bug, can't modify innerHTML of style-tags
			target = [];
			}

		    $('#background-style').attr('rel', 'alternative');
                    if (!target.length) 
		    	target = $('<style id="style-bg-css" type="text/css">' + data + '</style>').appendTo('head');
		    else
		    	target.html(data);
                    }
            });
    }

    setTimeout(function() { 
        inputs.change(preview_bg).filter('*[type=radio]').click(preview_bg);
    }, 100);

    var dialog_check = setInterval(function() { 
            if (!$('#styles:visible').length) { 
                $('#style-bg-css').remove(); 
		$('#background-style').attr('rel', 'stylesheet');
                clearInterval(dialog_check);
            }}, 1000);
    bg_toggle();
    preview_bg();

    if ($('#background_choices').is('.new_image'))
    {
	    $('#use_bg').click(function() { $('#background_choices').removeClass('new_image'); });
	    $('#background_choices > div.images').hide();
    }
}

function style_init_editor() 
{
    var editor = $('#style-editor table.editor');
    var rows = $('tr', editor);
    rows.filter('.section').click(function() {
            var $this = $(this);
            var toggler = $this.find('span.toggler');
            if (toggler.length)
                toggler[0].innerHTML = (toggler[0].innerHTML.charAt(0) == '+') ? '- ' : '+ ';
            for (var i = rows.index($this) + 1; i < rows.length; i++)
            {
                var cur = $(rows[i]);
                if (cur.is('.section'))
                    break;
                cur.toggle(); 
            }
    }).children('th').prepend($('<span class="toggler">+ <\/span>'));

    var colorpicker;

    editor.find('input:text').keyup(function() {
	    if (this.value.length != 4 && this.value.length != 7)
		    return;
	    try{
            $('span', this.parentNode).css('backgroundColor', this.value);
	    } catch(e){}
    }).focus(function() {

	    var self = this;
	    var color = (this.value.length < 4) ?  $('span.fallback', $(this).parents('tr')).text() : this.value;
	    colorpicker.linkTo(function(color) {
		    self.value = color;
		    $(self).keyup();
	    }).setColor(color);

	    $('#picker').css('display', 'block');
	    $(this.parentNode).append($('#picker'));

    }).keyup();

    $('tr.actions .use-fallback', editor).click(style_editor_fallback);
    $('tr.actions .clear', editor).click(style_clear_editor);

    $('#preview').click(function() {
        style_preview.call(this, editor);
    });

    rows.not('.section').hide();

    $('form#save-style').submit(function() {
        return confirm('Du kommer inte kunna göra några ändringar efter att du skickat in ditt tema');
    });

    $('head').append('<link rel="stylesheet" href="/static/js/lib/farbtastic/farbtastic.css" />');

    $.getScript('/static/js/lib/farbtastic/farbtastic.js', function() {
	    colorpicker = $.farbtastic('#picker');
    });
}

function style_toggle_editor()
{
    $('tr.section', '#style-editor table.editor').click();
}

function style_preview(editor)
{
    var button = this;
    if (button.disabled) return;

    $.post('/style/preview/update', $('input', editor).serialize(), function() {

            var append = parseInt(Math.random() * 1000);

            var css_url = '/style/preview/css/style.css?' + append;

            $('link#cssedit').remove();
            var stylesheet = $('<link id="cssedit" rel="stylesheet" href="' + css_url+ '" type="text/css" />');
            $('head').append(stylesheet);

            var images = $('img:visible', 'body > *:not(#widgetcontent), div.toolbar').each(function() {
                    this.origSrc = this.src;
                    this.src = this.src.replace(/.*?\/(img\/.*)/, '/style/preview/$1?' + append);
                });
            var lb_opacity = $('#lightbox-bg').css('opacity');
            $('#lightbox-bg').css('opacity', 0);

            var bgstyle = $('#background-style');
            var orig_bg = bgstyle.html();
            bgstyle.html('');

            $('#style-editor').hide();
            $('#style-preview-form').show();
            $('#style-preview-form input:submit').click(function() {
                handle($('#style-editor form:eq(1)')[0]);
            });

            $('#style-preview-form input.clear').click(function() {
                    $('#lightbox div.dialog').show();
                    $('#lightbox-bg').css('opacity', lb_opacity);
                    images.each(function() { this.src = this.origSrc; });
                    bgstyle.html(orig_bg);
                    stylesheet.remove();
                    $('#style-editor').show();
                    $('#style-preview-form').hide();
            });

        });
}

function style_editor_fallback()
{
    $('#style-editor table.editor tr').each(function() {
        $('input:text', this).val($('span.fallback', this).text());
    });
}

function style_clear_editor()
{
    $('#style-editor table.editor input:text').val('#');
}

$(function() {
    if ($.browser.msie && $.browser.version < 7)
        $('#opacity-style').remove();
});
;/* styles/base/js/style.js */
