$(function(){
    init_document();
});

function init_document() {
	window.defaultStatus="Design + Programming by FEINHEIT kreativ studio - www.feinheit.ch";
    if (!ie6) {
        $('#exex div.expander > .title, #exex div.subexpander > .title').click(function(){
            var body = $(this).next();
            var expander = $(this.parentNode);
            if(body.is(':visible')) {
                body.slideUp('fast', function(){expander.removeClass('expanded');});
            } else {
                expander.addClass('expanded');
                body.slideDown('fast');
            }
        });
    }
	if(typeof( COLLAPSE_STATUS_COOKIE ) != 'undefined') {
		init_collapse_status(COLLAPSE_STATUS_COOKIE);
	}

    if ($.browser.msie)
        $.facebox.settings.overlay = false;
    else
        $.facebox.settings.opacity = 0.7;

	var navigation_info = $('#navigation-info');
	var navigation_info_original = navigation_info.html();
	var navigation_info_new = '';
	$('#navigation a, #home-button').each(function(){
        $(this).data('subtitle', $('<div>'+this.title+'</div>').html()); // save unescaped HTML
        this.title = '';
	}).hover(function(){
        navigation_info_new = $(this).data('subtitle');
        navigation_info.fadeOut('fast', function(){$(this).html(navigation_info_new).fadeIn('fast');});
	}, function(){
	    navigation_info_new = navigation_info_original;
        navigation_info.fadeOut('fast', function(){$(this).html(navigation_info_new).fadeIn('fast');});
	});

    $('a.dialog').click(function(){
        return show_dialog(this.href);
    });

    $('div.items-3col > .item-3col').click(function(){
        window.location.href = $('a', this).attr('href');
    });

    expander_init_entries();

    init_rating();

    $.preloadCssImages();
}

function init_collapse_status(cookie_name) {

	if (typeof Object.prototype.toSource == 'function') {
			// expand the saved boxes
			if($.cookie(cookie_name)) {
				set_expanded(eval(($.cookie(cookie_name))));
			}
			// make sure to set the current collapse status
			$(window).unload(function(){
				set_cookie_collapse_status();
			});
	}
}

function set_cookie_collapse_status(){
		src = get_expanded().toSource();
		$.cookie(COLLAPSE_STATUS_COOKIE, src);
}

function expand_all(expand) {
    if (expand)
        $('#exex div.expander, #exex div.subexpander').not('.expanded').find('.title').trigger('click');
    else
        $('#exex div.expander.expanded > .title, #exex div.subexpander.expanded > .title').trigger('click');
    return false;
}

var dialog_params = {};
function show_dialog(url) {
    $.facebox(function(){
        $.get(url, dialog_params, function(data) {
            $.facebox(data);
            init_dialog();
        });
    });
    return false;
}

function init_dialog() {
    $('#facebox div.footer').remove();

    $('#dialog form').bind('submit', function() {
        return submit_dialog_form(this);
    });

    // bind handlers -- action defined by class name
    $('#dialog a.submit').click(function(){
        if (this.id)
            $('#action').val(this.id);
        $('#dialog form').submit();
        return false;
    });

    $('#dialog a.hide').click(function(){
        $.facebox.close();
        return false;
    });

    $('#dialog a.delete').click(function(){
        if(confirm(REALLY_DELETE_MESSAGE)) {
            var form_url = $('#dialog form').attr('action');

            if (form_url.indexOf('?')==-1)
                form_url += '?';

            $.post(form_url + '&delete=1', function(data) {
                $.facebox(data);
                init_dialog();
            });
        }

        return false;
    });

    // initialize date input fields
    $('#dialog input[name*=date]').addClass('date_inp').datepicker({
        dateFormat: 'dd.mm.yy',
        changeMonth: true,
        changeYear: true
        });

    // add classes to all input fields, so that we do not suffer from IE stupidity too much
    $('#dialog input').each(function(){ this.className += ' ' + this.type; });

    /*/ error highlighting
    $('#dialog div.error li').hover(function(){
        $('#dialog_' + this.id.substr(6)).effect('highlight', {color: '#FCF31C'}, 1000);
    }, function(){
    });
    */

    if (!$('#facebox a.close').length)
        $('#facebox td.body').append('<a class="close" href="#" onclick="$.facebox.close();return false"></a>');

    if (!$('#facebox table.decide-items tr#filler').length)
        $('#facebox table.decide-items').append('<tr id="filler"><td colspan="2"></td></tr>');

    dialog_decide_vertical_fill();
}

function submit_dialog_form(form) {
    $(form).ajaxSubmit({
        success: function(data) {
            $.facebox(data);
            init_dialog();
        }
    });
    return false;
}

// create global var
var dialog_decide_cfg = [];
var dialog_decide_fn = null;

function dialog_decide_init(cfg, fn) {
    inputs = $('#dialog div.decide-radio input');

    dialog_decide_cfg = cfg;
    dialog_decide_fn = fn;

    inputs.click(dialog_decide_show);

    var selected = inputs.filter('[checked]')[0];

    // select first radio button by default
    if (typeof(selected) == 'undefined') {
        selected = inputs[0];
        selected.checked = true;
    }

    dialog_decide_show.apply(selected);
}

function dialog_decide_show() {
    var fields = dialog_decide_cfg[this.value];
    if (!fields)
        return false;

    $('#dialog div.decide-radio').find('.selected').removeClass('selected');
    $(this).parents('li').addClass('selected')

    var rows = $('#dialog div.decide-radio').next().find('tr');
    var visible = rows.filter(':visible');

    if (visible.length)
        visible.hide();
    else
        rows.hide();

    dialog_decide_show_helper(fields);

    if (dialog_decide_fn)
        dialog_decide_fn.apply(this);

    dialog_decide_vertical_fill();

    var elem = $('#dialog').parent();

    setTimeout(function(){
        elem.style = 'display:block;';
        $(elem).show();
        $(elem).children().show();
    }, 100);

    return true;
}

function dialog_decide_show_helper(fields) {
    for(var i=0; i<fields.length; i++) {
        var id = fields[i][0];
        var title = fields[i][1];

        if (title)
            $('label[for=id_' + id + ']').html(title);

        $('#dialog_' + id).show();
    }
}

var dialog_height = 0;

function dialog_decide_vertical_fill() {
    var filler = $('#facebox table.decide-items tr#filler');

    if (filler.length) {
        filler.show();

        var dialog = $('#facebox div.content');
        var dialog_offset = dialog.offset();
        if (!dialog_height)
            dialog_height = dialog.height();

        var table_offset = $('#facebox table.decide-items').offset();
        var filler_offset = filler.offset();
        var buttons_height = $('#facebox div.buttons').height();

        filler.find('td').css('height', Math.max(0,
            dialog_height - buttons_height - (filler_offset.top - dialog_offset.top) - 15));
    }
}

$.preloadCssImages = function(){
    var allImgs = [];//new array for all the image urls
    var k = 0; //iterator for adding images
    var sheets = document.styleSheets;//array of stylesheets

    for(var i = 0; i<sheets .length; i++){//loop through each stylesheet
        var cssPile = '';//create large string of all css rules in sheet
        var csshref = (sheets[i].href) ? sheets[i].href : 'window.location.href';
        var baseURLarr = csshref.split('/');//split href at / to make array
        baseURLarr.pop();//remove file path from baseURL array
        var baseURL = baseURLarr.join('/');//create base url for the images in this sheet (css file's dir)
        if(baseURL!="") baseURL+='/'; //tack on a / if needed
        if(document.styleSheets[i].cssRules){//w3
            var thisSheetRules = document.styleSheets[i].cssRules; //w3
            for(var j = 0; j<thisSheetRules.length; j++){
                cssPile+= thisSheetRules[j].cssText;
            }
        }
        else {
            cssPile+= document.styleSheets[i].cssText;
        }

        //parse cssPile for image urls and load them into the DOM
        var imgUrls = cssPile.match(/[^\(]+\.(gif|jpg|jpeg|png)/g);//reg ex to get a string of between a "(" and a ".filename"
        if(imgUrls != null && imgUrls.length>0 && imgUrls != ''){//loop array
            var arr = jQuery.makeArray(imgUrls);//create array from regex obj
            jQuery(arr).each(function(){
                allImgs[k] = new Image(); //new img obj
                allImgs[k].src = (this[0] == '/' || this.match('http://')) ? this : baseURL + this;     //set src either absolute or rel to css dir
                k++;
            });
        }
    }//loop
    return allImgs;
}

function get_expanded() {
    var e = [[], []];

    var expanders = $('div.expander');
    var expanded = expanders.filter('.expanded');

    for(var i=0; i<expanded.length; i++)
        e[0].push(expanders.index(expanded[i]));

    expanders = $('div.subexpander');
    expanded = expanders.filter('.expanded');

    for(var i=0; i<expanded.length; i++)
        e[1].push(expanders.index(expanded[i]));

    return e;
}

function set_expanded(e) {
    var expanders = $('div.expander');

    for(var i=0; i<e[0].length; i++)
        $('> .title', expanders[e[0][i]]).trigger('click');

    expanders = $('div.subexpander');
    for(var i=0; i<e[1].length; i++)
        $('> .title', expanders[e[1][i]]).trigger('click');
}

function expander_init_entries() {

	$('#exex div.body.entries').each(function(){
        var dialog_buttons = $('div.buttons a.dialog', this);

        $('div.entry', this).click(function(){
            /* Class should either be id42-1 or id42 */

            var id = 0;
            var button_id = 0;

            var matches = this.className.match(/id(\d+)-(\d+)/);

            if (matches) {
                id = matches[1];
                button_id = matches[2];
            } else {
                id = this.className.match(/id(\d+)/)[1];
            }

            var dialog_url = dialog_buttons.filter(':eq(' + button_id + ')').attr('href');

            if (dialog_url && id)
                show_dialog(dialog_url + id + '/');

            return false;
        });
    });

    var entries = $('#exex div.entry, #selectedmeasures-list div.measure');
    entries.find('strong').not('.co2, .edit').addClass('co2').after('<strong class="edit"><img src="/media/images/co2m-edit-icon.png" alt="edit" /></strong>');
    entries.find('strong.edit').hide();
	entries.hover(function(){
        $('strong.co2', this).fadeOut('fast');
        $('strong.edit', this).fadeIn('fast');
    }, function(){
        $('strong.co2', this).fadeIn('fast');
        $('strong.edit', this).fadeOut('fast');
    });
}

function init_rating() {
    var rating = $('#rating');

    if (!rating.length)
        return;

    rating.addClass('clearfix');

    var initial_value = parseInt(rating[0].className.match(/r(\d+)/)[1]);
    var animating = false;

    var set_value = function(v, animate) {
        if (animating && !animate) return;

        if (animate)
            $('span', rating).animate({width: 23*v}, function(){animating=false;});
        else
            $('span', rating).css('width', 23*v);
    }

    set_value(initial_value);


    rating.left = rating.offset().left;
    rating.click(function(e){
        initial_value = parseInt((e.clientX - rating.left - 4) / 23.0) + 1;

        set_value(0);
        animating = true;
        setTimeout(function(){ set_value(initial_value, true); }, 1000);

        return false;
    }).mousemove(function(e){
        set_value(parseInt((e.clientX - rating.left - 4) / 23.0) + 1);
    }).mouseout(function(){
        set_value(initial_value);
    });
}

function jqplot_find_max(value) {
    var max = 500;
    while(max < value)
        max *= 2;
    return max;
}

function extract_from_array(array, idx) {
    var ret = [];
    for(var i=0; i<array.length; i++)
        ret.push(array[i][idx]);
    return ret;
}
