$(function(){
    $('form input').each(function(){ this.className += ' ' + this.type; });
    init_document();
});

slideToggleSpeed = 'fast';
timeouts = {};

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(slideToggleSpeed, function(){expander.removeClass('expanded');});
                expander.trigger('unexpand');
            } else {
                expander.addClass('expanded');
                body.slideDown(slideToggleSpeed, resize_jqplot_targets);
                expander.trigger('expand');
            }

            set_cookie_collapse_status();
        });
    }

    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');});
	});*/

    init_hover_menu();

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

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

    init_selects();
    expander_init_entries();
    init_rating();
	init_balloon_animation();

    // styled selectboxes
    $('select.selectbox').sb({fixedWidth:true});

	// tooltip hover menu
	$('.tooltip_hover').tooltip();

    //$.preloadCssImages();
}


function init_hover_menu() {
    HOVER_TIMEOUT = 200;

    var $ni = $('#navigation-info');

    $('a.mainnav').hover(function() {
        var e = $('#' + this.rel);
        $('.subnavigation:visible').not(e).clearQueue().slideUp();
        e.css('height', 'auto').slideDown('fast').hover(function(){}, function(){
            $(this).slideUp('fast');
        });
        $ni.fadeOut('fast')
    }, function() {
        timeouts[this.rel] = setTimeout(function() {
            var e = $('#' + this.rel);
            e.slideUp('fast');
            delete timeouts[this.rel];
        }, HOVER_TIMEOUT);
    });

    // hide everything when moving towards the top
    $('#pagetop').hover(function() {
        $('.subnavigation:visible').clearQueue().slideUp();
    }, function() {
    });

    $('.subnavigation ul li:not(.mark) ul').hide();
    $('.subnavigation ul li').hoverIntent(function () {
      if ($(this).hasClass('mark')) return;
      $('ul', this).slideDown('fast');
    }, function () {
      el = this;
      setTimeout(function () {
        if ($(el).hasClass('mark')) return;
        $('ul', el).slideUp('fast');
      }, 500);
    });
    $('.subnavigation ul ul').prev('a').addClass('withsubsub');
}

var balloon_animation_interval;
var balloon = {
	x: 30,
	y: 80,
	i: 0,
    v: true, // is visible
	e: null // jQuery element
}
function balloon_animation() {
	b = balloon;
	b.x += Math.sin(b.i/2) / 10;
	b.y += Math.cos(b.i) / 4
	b.i += 0.01;
	b.e.css({'right':b.x+'px', 'top':b.y+'px'});

    if ($(window).width() < 1100 && b.v) {
        b.e.hide();
        b.v = false;
    } else if ($(window).width() > 1100 && !b.v ){
        b.e.show();
        b.v = true;
    }
}

function init_balloon_animation() {
	b = $('#balloon');
	balloon.e = b;
	balloon.i = Math.random()*2;
	//balloon.x = document.body.clientWidth - b.position().left;
	//balloon.y = b.position().top;
	balloon_animation_interval = setInterval(balloon_animation, 1000/20);
}

function bind_correction_suggestion_actions() {
    $('ul.suggestions li').hover(function () {
        var action = $(this);
        action.click(function() {
            if (action.attr('type') == "CHANGE_VALUE") {
                $("#"+action.attr('field')).val(action.attr('to'));
            }

            action.css({'text-decoration': 'line-through'});
        });
    })


}

var select_timer;
function init_selects() {
    if($.browser.msie) {
        $('#id_habitation_type, #id_heating_profile, #dialog #id_purchase_type').hover(function(){
            if (select_timer)
                clearTimeout(select_timer);
            $(this).css('width', 'auto');
        }, function(){
            var select = this;
            select_timer = setTimeout(function(){
                $(select).css('width', '172px');
            }, 3000);
        });
    }
}

function init_collapse_status(cookie_name) {
    // expand the saved boxes
    if($.cookie(cookie_name)) {
        set_expanded($.evalJSON($.cookie(cookie_name)));
    }
    // make sure to set the current collapse status
    $(window).unload(function(){
        set_cookie_collapse_status();
    });
}

function set_cookie_collapse_status(){
		src = $.toJSON(get_expanded());
		$.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', {
                csrfmiddlewaretoken: $('#csrftoken input').val()
            }, 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
    $('form 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();

    init_selects();

    var currentHeight = $("#main").css('height');
    $("#main").css({'height': currentHeight});

    slideToggleSpeed = 0;

    // Hide tooltips if still active
    $("#divToolTip").hide();
}

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);

    bind_correction_suggestion_actions();
}

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

        try {
	        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;
	        }
        } catch(err) {
        	/* Security Exceptions */
        }

        //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');
    });

    push_nocarperiods_to_correct_order();
    push_estimations_to_correct_order();

}

function push_estimations_to_correct_order() {
    $('#exex div.body.entries').each(function(i, container) {
        $('div.estimation', container).each(function (i, element) {
            var show_before = $(element).attr('rel');
            if (show_before != null && show_before != '') {
                var target = $('div.entry.'+show_before,container);
                target.before(element);
            }
        });
    });
}

function push_nocarperiods_to_correct_order() {
    $('#exex div.body.entries').each(function(i, container) {
        $('div.ncp', container).each(function (i, ncp) {
            var moved = false;
            $('div.car', container).each(function(i, car) {
                if ( parseInt($(ncp).attr('rel')) > parseInt($(car).attr('rel')) ) {
                    $(car).before($(ncp));
                    moved = true;
                    return false;
                }
            });
            if (!moved) {
                var divs = $('div.car, div.estimation', container);
                if (divs.size() > 0) {
                    $(divs[divs.length-1], container).after($(ncp));
                }
            }
        });
    });
}


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;
}

function whole_year(from, to, year) {
    $('#'+from).val('01.01.' + year);
    $('#'+to).val('31.12.' + year);
}

function resize_jqplot_targets() {
	$('div.jqplot-target').each(function(){
        $t = $(this);
        $c = $t.find('canvas');
        $t.width($c.width());
        $t.height($c.height());
    });
}

function color_for_ratio(ratio) {

  if (ratio < 1) {
    ratio = Math.max(0.5, ratio);
    offset = 1 - ((2 * ratio) - 1);
    r = parseInt(253 + 68  * -offset);
    g = 240;
    b = 100;

  } else {
    ratio = Math.min(2, ratio);
    offset = 1 - (ratio - 1);
    r = parseInt(207 + 46  * offset);
    g = parseInt(27 + 212 * offset);
    b = parseInt(0 + 100 * offset);
  }

  return [r, g, b]
}

function roundToNthDecimal(value, decimals) {
    return Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals)
}

