
// questions can be treated by catogery or as whole bunch. Eather way they can also be randomized or kept in order
// as delivered in the data
var orderQuestions = 'cat-rand-all'; // false: keep order as delivered
                                 // 'cat' : group by categories, leaving order within category as delivered
                                 // 'rand-cat' : randomize within categories, leaving categories together
                                 // 'cat-rand-all' : select by categories, but randomize questions allover
                                 // 'rand-all' : randomize all questions allover

// amount of Trickquestions and other questions.
// IMportant: if "orderQuestions" is 'cat' or 'rand-cat', this value is interpreted as "per category"
var numberOfQuestions  = 3;      // how many questions we want to ask. Set this to 0 if you want all questions.
var numberOfTrickquest = 1;      // minimum number of Trickquestions



var fadeTime           = 150; 
var slideTime          = 450;
var myWidth            = 320;    // default widget width, can be set with GET variable width
var myLang             = 'de';   // default widget language, can be set with GET variable lang
var availableLang      = {       // object with available languages and their corresponding typo3 page id
    'de' : 59,
    'fr' : 73,
    'it' : 74
}

//var imageFolder        = "https://www.cheminfo.ch/";
var imageFolder        = "https://www.cheminfo.ch/";
//var serverUrl          = 'https://www.cheminfo.ch/risikotest';
var serverUrl          = 'https://www.cheminfo.ch/risikotest';

var myStrings = {
    'de' : {
        'nextQuestion'  : 'nächste Frage',
        'yourAnswer'    : 'Ihre Antwort ist: ',
		'rightAnswer'	: 'RICHTIG!',
		'wrongAnswer'	: 'LEIDER FALSCH...',
		'restart'		: 'Neu starten',
        
        'createCert'           : 'Zertifikat erstellen',
        'certificate_username' : 'Bitte Vorname und Name eingeben',
        'certificate_submit'   : 'OK',
        'certificate_filename'  : 'Zertifikat.pdf' ,
        'fb_lang'              : 'de_DE',
        
        
        'action_download' : 'Herunterladen',
        'action_share'    : 'Teilen',
        
        //'share_fb_link'        : 'https://cheminfo.ch/risikotest.html',
        'share_fb_link'        : 'https://www.cheminfo.ch/risikotest.html',
        'share_fb_title'       : 'Risikotest erfolgreich bestanden! Und Du?',
        'share_fb_caption'     : 'www.cheminfo.ch',
        //'share_fb_caption'     : 'cheminfo.ch',
        'share_fb_description' : 'Mach den Risikotest und prüfe Dein Wissen rund um die neuen Gefahrensymbole',
      
        
        
    },
    'fr' : {
        'nextQuestion'  : 'question suivante',
        'yourAnswer'    :  'Vous avez répondu :',
		'rightAnswer'	: 'BONNE RÉPONSE!',
		'wrongAnswer'	: 'MAUVAISE RÉPONSE...',
		'restart'		:'Redémarrer',
        'createCert'           : 'Créer un certificat',
        'certificate_username' : 'Veuillez saisir votre prénom et nom',
        'certificate_submit'   : 'OK',
        'certificate_filename'  : 'Certificat.pdf' ,
        'fb_lang'              : 'fr_FR',
        
        'action_download' : 'télécharger',
        'action_share'    : 'partager',        
        
        'share_fb_link'        : 'www.cheminfo.ch/fr/test-en-ligne.html',
        'share_fb_title'       : 'J\'ai réussi le test de risque. Et toi ?',
        'share_fb_caption'     : 'www.infochim.ch',
        'share_fb_description' : 'Fais le test et évalue tes connaissances sur les nouveaux symboles de danger.',        
        
        
    },
    'it' : {
        'nextQuestion'  : 'prossima domanda',
        'yourAnswer'    :  'Hai risposto: ',
		'rightAnswer'	: 'RISPOSTA CORRETTA!',
		'wrongAnswer'	: 'RISPOSTA ERRATA...',
		'restart'		: 'Riavviare',
        'createCert'           : 'Crea certificato',
        'certificate_username' : 'Inserire il nome e cognome',
        'certificate_submit'   : 'OK',
        'certificate_filename' : 'Certificato.pdf',
        'fb_lang'              : 'it_IT',
        'action_download'      : 'scaricare',
        'action_share'         : 'condividi',     
        
        'share_fb_link'        : 'https://www.cheminfo.ch/it/test-in-rete.html',
        'share_fb_title'       : 'Ho superato il test sul rischio! E tu?',
        'share_fb_caption'     : 'www.infochim.ch/it',
        'share_fb_description' : 'Prova a fare il test e scopri quanto sai sui nuovi simboli di pericolo.',           
        
    }
}

var myDebug = false;

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//var questions      = new Array(); // object with final pulished questions
var allQuestions   = {};          // object with all questions
var qIds           = new Array(); // array with all questionsIDs
var qFollowers     = new Array(); // array with all questionIds that are follower of another question
var analysis       = {};          // object with all analysis
var categories     = {};          // object with all categories
var score          = 0;           // the current score
var totalQuestions = 0;           // the amount of really picked questions (which can be higher due to follower questions)

var applyCustomWidth = false;     // falls eine andere breite gewünscht ist.

$(document).ready(function() {
    
    //
    calculateWidth();
    
    //
    if (GET('lang') != '') {
        if (availableLang[GET('lang')] > 0) {
            myLang = GET('lang');
        }
    }

    $('#startItem_' + myLang).fadeIn(100, function() {
        $('#startItem_' + myLang + ' img').fadeIn(1500);
    });
    var myTitle = $('#startItem_' + myLang + ' > h1').text();
    $(document).attr("title", myTitle);

    myLog('gettopbar: ' + GET('notopbar'));
    if (! (GET('notopbar') === '1')) {
        $("<h1/>").prependTo("#wrap").text(myTitle).addClass("gradient");
    }
    
    
    //if (application_data) {
    if (typeof application_data != 'undefined') {

        //localhost - download version der app
        // application_data is set on the downloaded app (zip)
        
        var lang_key = availableLang[myLang];
        data = application_data['questions'][lang_key];
        
        imageFolder = application_data['imageFolder'];
        
        //go
        
        var questions = prepareQuestions(data);
        fillQuestions(questions);
        
        
    } else {
        
        //browser
    
        // load the questions/answer data
        $.getJSON('content/data' + availableLang[myLang] + '.json', function(data) {    
            var questions = prepareQuestions(data);   
            // question array ready now for output
            fillQuestions(questions);
        
        
        });
         
         
    }
    
    //initially
    updateReachability();
    
    //create a certificate
    jQuery('body').on('click', '.createcertificate', function(evt){
        
        //show the form
        jQuery('form.certificate').slideDown('fast', function(){
            jQuery('html,body').scrollTop(jQuery(document).height());
        });
        
        
        
        
        evt.preventDefault();
        return false;
    });

    
    jQuery('body').on('click', '.actions .download', function(evt){
       
        //check if we are on mobile device
        if (jQuery('body').hasClass('opt-mobile')) {
            
            
            if (typeof RisikoTestInterface != 'undefined') {
                try {
                    RisikoTestInterface.downloadCertificate(certInfo['file']);
                } catch (e) {}
                
            } else {
        
                try {
                    var frame = createCallbackFrame();
                    frame.src = 'ch.cheminfo.risikotest.js.event:///download-certificate';
                } catch (e) {}
            
            }
            
            
            
            evt.preventDefault();
            return false;
            
        } else {
            
            //do nothing
        
        }       
        
        
    });
    
    
    jQuery('body').on('click', '.actions .share', function(evt){
        
        if (certInfo == null) return;

        //check if we are on mobile device
        if (jQuery('body').hasClass('opt-mobile')) {

            if (typeof RisikoTestInterface != 'undefined') {
                try {
                    RisikoTestInterface.shareCertificate(certInfo['file']);
                } catch (e) {}
                
            } else {
            
                try {
                    var frame = createCallbackFrame();
                    frame.src = 'ch.cheminfo.risikotest.js.event:///share-certificate';
                } catch (e) {}            
                
            }
            
            
        } else {
            
        
            //DESKTOP
            FB.ui({
                method  : 'feed',
                picture : certInfo['thumb'] ,
                link    : myStrings[myLang]['share_fb_link'],
                name    : myStrings[myLang]['share_fb_title'],
                caption : myStrings[myLang]['share_fb_caption'],
                description: myStrings[myLang]['share_fb_description'],
            }, function(response){
            
            });              
            
        }
        
        

        
      

        
        
        evt.preventDefault();
        return false;
    });    
    
    jQuery('body').on('submit', 'form.certificate', function(evt){
        
        var username = jQuery('input[name=username]', jQuery(this)).val();
        if (username.length < 1) return false;
        
        sendCertificateRequest(username);
        
        evt.preventDefault();
        return false;
    });
    
    jQuery('body').on('click', 'form.certificate button', function(evt){
        
        var username = jQuery('input[name=username]', jQuery(this).parents('form')).val();
        if (username.length < 1) return false;
        
        sendCertificateRequest(username);        
        
        evt.preventDefault();
        return false;        
    });
    
    
    
    
    initFacebook();//Share
        
});

/*jQuery(document).on('offline online', function(evt) {
    console.log('documents');
    updateReachability();
});*/
jQuery(window).on('offline online', function(evt) {
    updateReachability();
});
        

function calculateWidth()
{
    
    if (typeof(GET("width")) != 'undefined') {
        
        var customWidth = GET("width");
        if (isNaN(customWidth)) {
            
            if (customWidth.indexOf("p") == 0) {
                var factor = parseInt(customWidth.substr(1));
                myWidth = jQuery(document).width() * (factor*1.0/100.0);
                applyCustomWidth = true;
            }
        } else {
            myWidth = Math.floor(customWidth);
            applyCustomWidth = true;
        }
        
    }    
    
}
        
        


function prepareQuestions(data) {
    analysis = data.analysis;
    categories = data.categories;
    allQuestions = data.questions;
    questions = new Array();
    myLog("analysis: " + analysis[1]);
    // count questions, fill array "qIds" with its ID
    $.each (categories, function(i) {
        categories[i]['questions'] = new Array();
        categories[i]['trickquestions'] = new Array();
    })
    
    $.each (data.questions, function(i) {
        qIds.push(i);
        if(data.questions[i]["followTo"] > 0) {
            qFollowers.push(data.questions[i]["followTo"]);
        }
        categories[data.questions[i]['category']]['questions'].push(i);
        if (data.questions[i]['trickquestion']) {
            categories[data.questions[i]['category']]['trickquestions'].push(i)
        }
    });
    myLog("array qIds is: " + qIds.toString());
    myLog("qIds lenght is: " + qIds.length);
    myLog("array qFollowers is: " + qFollowers.toString());
    
    
    if (orderQuestions === false || orderQuestions === 'rand-all') {
        questions = pickQuestions(qIds, numberOfQuestions);
        myLog("questions: " + questions.toString());
    } else {
        myLog("Categories are:");
        $.each (categories, function(i) {
            myLog("  " + categories[i]['categoryText']);
            myLog("    Questions: " + categories[i]['questions'].toString());
            myLog("    Trickquestions: " + categories[i]['trickquestions'].toString());
            temp = pickQuestions(categories[i]['trickquestions'],numberOfTrickquest);
            temp = temp.concat(pickQuestions(categories[i]['questions'],numberOfQuestions - temp.length));
            myLog("    temp: " + temp.toString());
            if (orderQuestions === 'rand-cat') {
                temp = array_shuffle(temp);
                myLog("    temp shuffled: " + temp.toString());
            }
            
            questions = questions.concat(temp);
        })
        
        if (orderQuestions === 'cat-rand-all') {
            questions = array_shuffle(questions);
        }
        
    }
    
    
    myLog("*** Final question IDs: " + questions.toString());
    return questions;
    
}

function pickQuestions(qPool, n) {
    // select questions 
    var ret = new Array();
    var i = 0;
    if (n == 0) {
        n = qPool.length;
    }
    myLog("select " + n + " questions out of " + qPool.toString());
    // loop through number of questions we want
    while (i < n && qPool.length) {
        myLog("--------- question number " + i);
        if (orderQuestions === 'rand-cat' || orderQuestions === 'rand-all' || orderQuestions === 'cat-rand-all') {
            r = Math.floor(Math.random() * qPool.length);
        } else {
            r = 0;
        }

        if (array_search(qPool[r],qIds) >= 0 && array_search(qPool[r],qFollowers) < 0) 
        { // we picked a unused question which is no follower of another question

            // get questionId by cutting the value fromt the qIds array.
            // This way, we avoid picking a question twice
            qId = (qPool.splice(r, 1)).toString();
            qIds.splice(array_search(qId, qIds),1);
            myLog("  catched question ID: " + qId);

            // copy the question data to our object
            ret.push(qId);
            //questions["q" + qId]  = allQuestions[qId];

            myLog("  array of available qPool is now: " + qPool.toString());
            myLog("  array of available qIds is now: " + qIds.toString());
            i++;

            // if a question has any sequential following question(s), we get it here
            while (allQuestions[qId]["followTo"]) {
                fq = allQuestions[qId]["followTo"];
                ret.push(fq);
                //questions["q" + fq] = allQuestions[fq];
                qId = fq;
                i++;
                qIds.splice(array_search(qId, qIds), 1);
                qPool.splice(array_search(qId, qPool), 1);
                myLog("    follower found: " + qId)
                myLog("    array of available qPool is now: " + qPool.toString());
                myLog("    array of available qIds is now: " + qIds.toString());
            }
        } else 
        { // we picked a follower question. Ignore!
            qId = (qPool.splice(r, 1)).toString();
            myLog("  picked a used question or a follower question. Ignore it: " + qId);
        }
        myLog("---------");
    }
    //myLog("EOF select the questions randomly");
    myLog("we picked " + i + " questions: " + ret.toString());

return ret;
}


function fillQuestions(qPool) {
    
    var c = 0;
    totalQuestions = qPool.length;
    var sProgress = '';
	var spanWidth = ((myWidth-totalQuestions*1)/totalQuestions);
    
    for (n in qPool) {
        q = allQuestions[qPool[n]];
        c++;
        questionItem = $("<li/>",{"id":"question"+c}).appendTo("#questionList").addClass("questionItem");
        questionItemText = $("<div/>").appendTo(questionItem);
        
        $("<img/>",{
            "src"    :  imageFolder+q.image, 
            "alt"    : "",
            "class"  : "retina"
        }).appendTo(questionItemText);
        progressItem = $("<div style=width:"+myWidth+"px;/>").appendTo(questionItemText).addClass("progress");
        for (i=0; i < totalQuestions; i++) {
            bulletItem = $("<span style=width:"+spanWidth+"px;>"+(i+1)+"</span>").appendTo(progressItem);
            if(i >= c) {
                bulletItem.addClass('inactive');
            }
            //sProgress = sProgress + "•";
        }
        //progressItem.html(sProgress.substring(0,c) + '<span class="toGo">' + sProgress.substring(c) + '</span>');
        $("<p/>").appendTo(questionItemText).text(q.questionText);
        
        // the answer container
        $("<ul/>",{"id":"answerList"+c}).appendTo(questionItem).addClass("answerItemList");   
        // loop through every answer
        $.each(q.answers, function(j, a) {
            answerItem = $("<li/>",{"id":"answer"+c+"-"+j}).appendTo("#answerList"+c).addClass("answerItem");
            $("<button/>",{"data-score":a.score, "data-question":c, "data-answer":j}).appendTo(answerItem).text(a.buttonText);
            answerItemText = $("<div/>").appendTo(answerItem);
            
            if(a.score==1) {
				$("<p class='rightAnswer title' />").appendTo(answerItemText).text(myStrings[myLang].rightAnswer);
				$("<p class='rightAnswer' />").appendTo(answerItemText).text(a.answerText);
			} else {
				$("<p class='wrongAnswer title' />").appendTo(answerItemText).text(myStrings[myLang].wrongAnswer);
				$("<p class='wrongAnswer' />").appendTo(answerItemText).text(a.answerText);
				//$("<h2/>").appendTo(answerItemText).text(a.answerText);
			}
        });
        $("<button/>",{"data-next":"question"+(c+1)}).appendTo(questionItem).text(myStrings[myLang].nextQuestion);
        
        
        
        
        //REMOVEME - limit to one question
        //break;
    }

    // at the end: append the analysis container as last element
    $("<li/>").appendTo("#questionList").addClass("questionItem endItem");

    // add click events to answer and next buttons
    $(".questionItem > button").click(function () {
        next($(this));
    });
    $(".answerItem > button").click(function () {
        answer($(this));
    });

    // adjust size for retina resolution
    retina_image_size();

    // adjust width if requested
    //if(GET("width") > 0) {
    if (applyCustomWidth == true) {
        adjust_width(myWidth);
    }
    
}



// called if answer was given. Update the score, hide the buttons and show the answer text
function answer(el) {
    
    //console.log('offeset html' + $('html').scrollTop());
    //console.log('offeset body' + $('body').scrollTop());  
    $('html,body').scrollTop(0);
    
    
    score += (el.attr("data-score") * 1);
    $(
        "#question" + el.attr("data-question") + " .answerItem button" + " , " +
        "#question" + el.attr("data-question") + " > div"
    ).fadeOut(fadeTime,function() {
        $("#answer" + el.attr("data-question") + "-"+el.attr("data-answer") + " div").fadeIn(fadeTime);
        $("#question" + el.attr("data-question") + " > button").fadeIn(fadeTime);
    });
}


// called if next question or analysis is requested
// fade and empty the current question container, slide everything to left
function next(el) {
    $('html, body').scrollTop(0);
    
    
    
    var nextID = el.attr("data-next");
    myLog("goto next question: " + nextID);
    if ($("#" + nextID).length > 0) {
        // check if there is a next question
        myLog($("#" + nextID).length);
        myLog("existing question");
    } else {
        // no question left: => analysis
        myLog($("#" + nextID).length);
        myLog("not existing question, so comes the analysis");
        
        
        
        var matchedResult = null;
        var masterTopHeroResult = null; //the highest possible result
        jQuery.each(analysis, function(index, value){
            if (matchedResult == null) { matchedResult = value; } //select at least one result
            if (masterTopHeroResult == null) { masterTopHeroResult = value; } //select at least one result
            
            if (value['max'] < score) {
                matchedResult = value;
            }
            
            if (value['max'] > masterTopHeroResult['max']) {
                masterTopHeroResult = value;
            }
            
        });

        myLog("analysisText: " + matchedResult.analysisText);
        myLog("analysisImage: " + matchedResult.image);
        myLog("analysisMax: " + matchedResult['max']);
        
        var userHasHighestPossibleResult = (masterTopHeroResult['max'] == matchedResult['max']);
        
        //REMOVEME - limit to one question
        //userHasHighestPossibleResult = true;
        
        

        var endItemText = $("<div/>").appendTo(".endItem");
        if (matchedResult.image.length > 0) {
            $("<img/>",{
                "src"    :  imageFolder+matchedResult.image, 
                "alt"    : "",
                "class"  : "retina avatar"
            }).appendTo(endItemText);
            retina_image_size();
        }
        
        
        $("<p/>").appendTo(endItemText)
            .text(matchedResult.analysisText);

            
            
            
        
            
        var buttonWrap = jQuery('<div>', {
            'class' : 'buttonwrap clearfix'
        }).appendTo(endItemText);
            

        if (userHasHighestPossibleResult) {
            //Certificate Button   
            $("<button/>",{
                'class' :'createcertificate'
            }).appendTo(buttonWrap)
              .text(myStrings[myLang]['createCert']);
        }
            
        
        $("<button/>",{
            "onclick":"window.location.reload()"
        }).appendTo(buttonWrap)
          .text(myStrings[myLang]['restart']);
            
        
        if (userHasHighestPossibleResult) {
        
            //container for certificate form
            var certForm = jQuery('<form>', {
                'class' : 'certificate',
                'method' : 'post'
            }).appendTo(endItemText)
              .append('<p><label for="username">'+myStrings[myLang]['certificate_username']+'</label></p>')
              .append('<input type="text" class="text" id="username" name="username">')
              //.append('<input type="submit" class="button" name="submit" value="'+myStrings[myLang]['certificate_submit']+'">');
              .append('<button class="button">'+myStrings[myLang]['certificate_submit']+'</button>');
        
            certForm.hide();
        
            jQuery('<div>', {
                'class' : 'actions'
            }).appendTo(endItemText);
            
        }
        
            
    }
    /* code for sliding */
    /*
    $(".questionItem").animate({
        left: '-=' + myWidth
    }, slideTime, function() {
        $(el).parent().empty();
    });
    */

    /* code for fading */
    $(el).fadeOut(fadeTime, function() {
        $(el).parent().remove();
        $("#" + nextID).fadeIn(fadeTime);

    });

}


// adjust images to the desired with of the main container
function retina_image_size() {
    $("img.retina").each(function(el){
        //myLog(el);
        //myLog($(this));
        var ob = $(this);
        src = $(this).attr("src");
        newImg = new Image();
        height = 0;
        width  = 0;
        newImg.onload = function() {
            //myLog(ob);
            factor = myWidth / this.width;
            width  = myWidth
            height = this.height * factor;
            //myLog("INNER real_image_size dimension: " + width + "x" + height);
            $(ob).attr({"width":width, "height":height});
        }
        newImg.src = src;
        
    });
}

// called to adjust the width of container elements and buttons
// to the desired with of the main container
function adjust_width(w) {
    
    $("#wrap").width(w);
    $(".questionItem").width(w - 56);
    $(".answerItem > div").width(w - 76);
    $(".answerItem button").css("min-width",Math.min(127, (myWidth - 66) / 2));
}


// find index of value in a array
function array_search(needle, arr) {
    for (var i=0 ; i < arr.length ; i++) {
        //myLog("array_search test: " + arr[i] + " == " + needle);
        if (arr[i] == needle) {
            //myLog("array_search returned "+i);
            return i;
        }
    }
    //myLog("array_search returned -1");
    return -1;
}
/*
function array_shuffle(a) {
  var i = a.length;
  //if ( i == 0 ) return false;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = a[i];
     var tempj = a[j];
     a[i] = tempj;
     a[j] = tempi;
   }
   return a;
}
*/
function array_shuffle(ary) {
    var s = new Array(); 
    while (ary.length) s.push(ary.splice(Math.random() * ary.length, 1)); 
    //while (s.length) ary.push(s.pop());
    return s;
}
// find get variable in URL string
function GET(name) {
    return unescape((RegExp(name + '=' + '(.+?)(&|$)').
    exec(location.search)||[,undefined])[1]);
}

function myLog(s) {
    //if (myDebug) {
    //    console.log(s);
    //}
    //console.log(s);
}


if (window.addEventListener) {
    window.addEventListener("orientationchange", function() {
        
        calculateWidth();
        adjust_width(myWidth);
        
        
    }, false);
}



//
function getDocumentTitleForAppNavigationTitle()
{
    var title = jQuery(document).attr("title");
    return title;
}



//checks if a internet connection is available
function updateReachability()
{
    
    var request = jQuery.ajax({
        'url'  : serverUrl + '/lib/img/reachability.png',
        'cache': false
    }).done(function( data, textStatus, jqXHR ){
        
        //console.log(textStatus);
        //console.log(jqXHR);
        
        //console.log(jqXHR.status == 200);
        
        jQuery('body').addClass('online').removeClass('offline');
        
    }).fail(function( jqXHR, textStatus, errorThrown ) {
        //console.log(errorThrown);
        jQuery('body').addClass('offline').removeClass('online');
        
    });
    
}


var certRequest = null;
var certInfo = null;
//upload user data
// server creates pdf document and returns download link
function sendCertificateRequest(username)
{
    if (certRequest !== null) return;
    
    
    //Erstelle die Optionen
    var endItem = jQuery('.endItem > div');    
    var actionWrap = jQuery('.actions', endItem);
    actionWrap.html('<img class="busy" src="lib/img/busy.gif">');
    
    
    
    var parameters = {
       'cert' : {
            'username': username,
            'score'   : score,
            'lang'    : myLang            
       }
    };
    
    certRequest = jQuery.ajax({
        type : "POST",
        url  : serverUrl + '/certificate/api/',
        data : parameters,
        dataType : 'json'
    }).done(function(data, textStatus, jqXHR ){
        
        if (data['code'] == '200') {
            
            certInfo = data;
            
            
            //var actionWrap = jQuery('.actions', endItem);  //jQuery('<div>', {'class' : 'actions'}).appendTo(endItem);
            actionWrap.empty();
            
            //Certificate Button   
            jQuery('<a>',{
                'class'    : 'button download' ,
                'href'     : certInfo['file'],
                'target'   : '_blank' ,
                'download' : '' + myStrings[myLang]['certificate_filename']
                
            }).appendTo(actionWrap)
              .text(myStrings[myLang]['action_download']);
            
            $("<button/>",{
                'class' :'share'
            }).appendTo(actionWrap)
              .text(myStrings[myLang]['action_share']);
            
            
            
            
        } else {
            actionWrap.empty();
            
        }
        
        
        
        
        
        certRequest = null;
        
    }).fail(function( jqXHR, textStatus, errorThrown ) {
        
        //jQuery('body').addClass('offline').removeClass('online');
        
        certRequest = null;
    });
    
        
}






window.fbAsyncInit = function() {
    FB.init({
        appId   : '318707224886712',
        xfbml   : true,
        version : 'v2.3'
    });
};

function initFacebook()
{    
    
    if (jQuery('body').hasClass('opt-mobile')) {    
        //console.log('mobile, no facebook share needed');
        return;
    } else {
        //console.log('initFacebook');
    }
    
    var d  = document;
    var s  = 'script';
    var id = 'facebook-jssdk';
    
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/"+myStrings[myLang]['fb_lang']+"/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);  
}


function injectConfiguration(configuration) 
{
    var options = configuration.split(',');
    
    var jqBody = jQuery('body');
            
    var currentOptions = jqBody.attr('class').split(/\s+/);
    jQuery.each(currentOptions, function(index, cssClass){
        if (cssClass.indexOf('opt-') == 0) {
            jqBody.removeClass(cssClass);
        }
    });

    //adding new options
    jQuery.each(options, function( index, value ) {
        var option = value.trim();
        if (option == '') return;
        
        jqBody.addClass('opt-' + option + '');
    });
    
}



function createCallbackFrame()
{

    var frameId = 'callback-frame';
    
    var frame = document.getElementById(frameId);
    if (frame == null) {

        
        frame = document.createElement('iframe');
        frame.setAttribute('id',frameId);
        frame.setAttribute('border','0');
        frame.setAttribute('style','display:none;');
        
        document.body.appendChild(frame);
    }
    
    return frame;
}


function native_getCertificateInfo()
{
    return JSON.stringify(certInfo);
}
