/*  ##############################################
    #  EXTENDED CORE        WWW.ENGLISH-STUDY.DE #
    # (c) 2010 Sebastian Felling, Germany        #
    ##############################################
*/
var strExCanvas = 'body.single div.entry div.exGap2';

jQuery(document).ready(function() {
    // check for exercise
    if($(strExCanvas).length > 0) {
        // prepare exercise
        ex_prepare();
    }
});

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>');
}

// 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;
}
