/*  ##############################################
    #  EXTENDED CORE        WWW.ENGLISH-STUDY.DE #
    # (c) 2010 Sebastian Felling, Germany        #
    ##############################################
*/
var strExCanvas = 'body.single div.entry div.exGap2';
var tb_closing;
var tb_disabled = false;
var slidebar_top_original = 0;

$(document).ready(function() {
    // replace category list
    listCatsReplace();

    // show tabs
    if($('#blog_menu_canvas').length > 0) {
        $('#blog_menu_canvas').removeClass('hidden');
    }
    
    // show toolbar
    if($('#toolbar').length > 0) {
        $('#toolbar').show();
    }
    
    // check for exercise
    if($(strExCanvas).length > 0) {
        // prepare exercise
        ex_prepare();
    }
    
    // initialize slidebar
    slidebar_init();
});

function listCatsReplace() {
    // hook up category dropdown
    if($('#cat').length > 0) {
        // show
        $('#cat').css('display', 'block');
        
        // hook up change event
        $('#cat').change(function() {
            // select category
            var intCatID = $('#cat').val();
            location.href = "/?cat=" + intCatID;
        })
    }
    
    // change min-size
    if($('#box_cats').length > 0) {
        $('#box_cats').css('min-height', '4em');
        $('#box_cats').css('height', '4em');
    }
    
    // hide list cats
    if($('#list_cats').length > 0) {
        $('#list_cats').css('display', 'none');
    }
}

function tab_change(intIndex) {
    // check if available
    if($('#tab_canvas').length > 0 && $('#tab_canvas .tab').length > intIndex) {
        // unclass + reclass all tabs
        $('#blog_menu li').removeClass('active');
        $('#blog_menu li:eq(' + intIndex + ')').addClass('active');
        
        // show new tab
        $('#tab_canvas .tab:eq(' + intIndex + ')').fadeIn();
        $('#tab_canvas .tab:eq(' + intIndex + ')').removeClass('hidden');
        
        // hide others
        for(var i = 0; i < $('#tab_canvas .tab').length; i++) {
            if(i != intIndex) {
                $('#tab_canvas .tab:eq(' + i + ')').hide();
            }
        }
    }
    
    // prevent default click behavior
    return false;
}
function ex_prepare() {
    // hide java warning
    $('#javawarning').hide();
    
    // find all spans
    $(strExCanvas + ' span').each(function() {
        // which gap type?
        if($(this).html().indexOf('$') > -1 || ($(this).html().indexOf('|') == -1 && $(this).html().indexOf('!') != 0 )) {
            // input box
            
            // retrieve all possible answers
            var strValues = $(this).html().split('$');
            var intMaxWidth = 0;

            // retrieve longest possible answers
            for(var i = 0; i < strValues.length; i++) {
                intMaxWidth = Math.max(intMaxWidth, strValues[i].length);
            }
            
            // add key
            $(this).html('<input type="text" class="gap" xml:key="' + strValues.join('|') + '" style="width: ' + parseInt(intMaxWidth * 0.6) + 'em;" />');
            
        } else if($(this).html().indexOf('|') > -1) {
            // select field
            // retrieve single values
            var strValues = $(this).html().split('|');
            
            // retrieve keys
            var strKeys = new Array();
            
            for(var i = 0; i < strValues.length; i++) {
                // is key?
                if(strValues[i].indexOf('*') > -1) {
                    strKeys.push(strValues[i].replace(/\*/g, ''));
                }
            }
            
            var list = $(this).html('<select class="gap"><option selected="selected"></option></select>');
            
            // shuffle
            strValues = array_shuffle(strValues);
            
            // iterate through values and add to select field
            $(strValues).each(function(index, val) {
                $(list).find('select').append('<option>' + val.replace(/\*/g, '') + '</option>');
            });
            
            // add key
            $(list).find('select').attr('xml:key', strKeys.join('|'));
            
        } else if ($(this).html().indexOf('!') == 0) {
            // info box
            // retrieve contents
            var strValue = $(this).html().replace(/\!/, '');
            
            // add class
            $(this).replaceWith('<a href="#" class="info">[?]<del>' + strValue + '</del></a>');
        }
    });
    
    // display spans
    $(strExCanvas).find('span').css('visibility', 'visible');
    
    // add score button
    $(strExCanvas).append('<div class="ex_buttons"><input type="button" value="Abgeben und auswerten" onclick="ex_exGap2_showScore()" class="submit" /></div>');
}

function ex_exGap2_showScore() {
    var intCorrect = 0;
    var intWrong = 0;

    // hide button
    $(strExCanvas).find('div.ex_buttons input.submit').remove();
    
    // iterate through spans
    $(strExCanvas + ' span ').each(function() {
        // remove classes
        $(this).children(':first').removeClass('wrong');
        $(this).children(':first').removeClass('correct');
        
        // get key
        var strKeys = $(this).children(':first').attr('xml:key');
        
        // check given input
        if(strKeys.split('|').contains($(this).children(':first').val())) {
            // correct
            $(this).children(':first').addClass('correct');
            intCorrect++;
            
        } else {
            // wrong
            $(this).children(':first').addClass('wrong');
            intWrong++;
        }
        
        // add title
        $(this).children(':first').attr('title', strKeys.split('|')[0]);
    });
    
    // alert
    var intTotal = intCorrect + intWrong;
    var intPercentage = parseInt(100 / intTotal * intCorrect);
    var strAlert = '<div class="score">' + intPercentage + '%</div><p>Du hast ' + intCorrect + ' von ' + intTotal + ' Lücken richtig beantwortet.<br />Die richtigen Lösungen siehst du auch, wenn du mit der Maus über ein Element fährst (Tooltip).</p>';
    
    // show explanation tooltips
    $(strExCanvas + ' a.info').each(function() {
        // show
        $(this).fadeIn();
    });
    
    // delete alerts
    $(strExCanvas).find('.ex_score').remove();
    
    // add alert
    $(strExCanvas).append('<div class="ex_score">' + strAlert + '</div>');
}

function tb_open() {
    // disabled?
    if(tb_disabled) return;
    
    // open toolbar
    tb_resize(300, true);
    
    // override default click behavior
    return false
}

function tb_newLookup() {
    // disabled?
    if(tb_disabled) return;
    
    // hide frame
    $('#tb_lookup').hide();
    
    // look up
    tb_open();
}

function tb_resize(intHeight, bolFadeIn) {
    // disabled?
    if(tb_disabled) return;
    
    $('#toolbar').animate({ height: intHeight + 'px' }, 300, function() {
                                        // fade in/out frame
                                        if(bolFadeIn) {
                                            // frame hidden? => fade in
                                            if($('#tb_lookup').css('display') == 'none') {
                                                $('#tb_lookup').fadeIn();
                                            };
                                            
                                            $('#button_close').css('visibility', 'visible');
                                            $('#button_open').css('visibility', 'hidden');
                                        } else {
                                            $('#button_close').css('visibility', 'hidden');
                                            $('#button_open').css('visibility', 'visible');
                                        }
                                    });
}

function tb_leaving() {
    // disabled?
    if(tb_disabled) return;
    
    tb_closing = window.setTimeout('tb_close()', 1000);
}

function tb_entering() {
    // disabled?
    if(tb_disabled) return;
    
    // clear timeout
    window.clearTimeout(tb_closing);
}

function tb_close() {
    // disabled?
    if(tb_disabled) return;
    
    // close toolbar
    tb_resize(30, false);
    
    // override default click behavior
    return false
}

function tb_disable() {
    var answer= confirm('Toolbar wirklich schließen?');

    if(answer) {
        // disable
        $('#toolbar').hide();
        tb_disabled = true;
    }
    
    // override default click behavior
    return false
}

// add contains prototype
// credit: http://www.experts-exchange.com/Database/Oracle/9.x/Q_22600837.html
if (!Array.prototype.contains){
    Array.prototype.contains = function(obj){
    var len = this.length;
    for (var i = 0; i < len; i++){
      if(this[i]===obj){return true;}
    }
    return false;
  };
}

// credit: http://jsfromhell.com/array/shuffle
function array_shuffle(v){
    for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
    return v;
};

// SLIDEBAR
function slidebar_init() {
    // slidebar active?
    if($('#slidebar').length == 0) return;
    
    // save initial top
    slidebar_top_original = $('#slidebar').offset().top;
    
    // show
    $('#slidebar').css('visibility', 'visible');
    
    // hook up window scroll event
    $(window).scroll(function() {
        try {
            fb_canvas_height = Math.max($('#canvas_fb').height(), 250);
        
            if($(window).scrollTop() > (slidebar_top_original + fb_canvas_height)) {
                intDiff = $(window).scrollTop() - slidebar_top_original;
                $('#slidebar').css('top', (intDiff - fb_canvas_height) + 'px');
            } else {
                $('#slidebar').css('top', '0');
            }
        } catch(err) {
            // release event hook
            $(window).unbind('scroll');
            
            // reset
            $('#slidebar').css('top', '0');
        }
    });
    
    // fire once
    $(window).scroll();
}
