var cfg = {
    scormHandler: null,
    pname: null,
    stat: 'rdy',
    draw: false
};

// dodac kod swfa ktory jest cwiczeniem
var questioncodes = [22,23];

var scorm = null;


var quiz = {};

create_qq();

if ( typeof sinit === "undefined"){
    scorm = pipwerks.SCORM;
} else {
    
    if(typeof sinit === "string" && sinit === "cookie"){
        cfg.scormHandler = "cookie";
        cfg.pname = pname;

    } else if (typeof sinit === "string" && sinit === "dscorm") {
        cfg.scormHandler = "dscorm";
        cfg.pname = pname;
    }
    
//    if (typeof loc !== "undefined") {
//        cfg.pname = pname;
//    }
    
    scorm = {
        init: function() {
            return false;
        },
        get: function() {
            return false;
        },
        set: function() {
            return false;
        },
        save: function() {
            return false;
        },
        quit: function() {
            return false;
        }
    };
}

var saveTime = 1;
var currentPageStatus = {
    page: 0,
    time: 0,
    page_time: {},
    start: function(p) {
        if (cfg.scormHandler == "dscorm") {
            var date = new Date();

            if (currentPageStatus.time != 0) {
                currentPageStatus.page_time[currentPageStatus.page] += date.getTime() - currentPageStatus.time;
                darkanscorm.data.page_time = JSON.stringify(currentPageStatus.page_time);
            }

            currentPageStatus.page = p;
            currentPageStatus.time = date.getTime();
        }
    }
};

//var aaaaa = {};
//if (Object.keys(aaaaa).length === 0) {
//    mylog('++++++++++++++++++++++++  obiekt jest pusty  +++++++++++++++++++++++++');
//    
//    for(i = 0; i < all; i++) {
//        aaaaa[i] = 0;
//    }
//}


//darkanscorm.data.page_time = {};

//var _gaq = _gaq || [];
//_gaq.push(['_setAccount', 'UA-29835033-2']);
//_gaq.push(['_setDomainName', 'website.pl']);
//_gaq.push(['_trackPageview']);

(function() {
//      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
//      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
//      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

var lmsConnected = false;


var debugmode = false;
var page_order = 0;
var page = strony[page_order][1];

var timeout;
var isNextBinded = false;
var isPrevBinded = false;

var offlineScore = 0;

// tworzenie tablicy statusow
//var mypointstatus = new Array();
//var strony = [];
var i, j;
var prevScreenFn, nextScreenFn;
var myLessonLocation;

var is_ie7 = 0;

//if (/MSIE (\d+\.\d+);/.test(navigator.userAgent))
if (navigator.appVersion.indexOf("MSIE 7.") != -1 ||
    navigator.appVersion.indexOf("MSIE 8.") != -1 ||
    navigator.appVersion.indexOf("MSIE 9.") != -1)
    is_ie7 = 1;

function handleError(msg){
   //alert(msg);
   //window.close();
}

// obsluga coookies ===========================================================

function createCookie(name, value, days) {
    var expires;

    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/;domain=darkan1.website.pl";
}

function readCookie(name) {
    var nameEQ = escape(name) + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return unescape(c.substring(nameEQ.length, c.length));
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}


function cross_browser_rotation(o) {
    var rot = o.find('.img-container').attr('rot');
    if ( typeof rot === "string" ) {
        var style = o.find('.img-container').attr('style');
        o.find('.img-container').attr('style', style + ';' + rot);
    }
}

function fire_before_enter(o) {
    // handle cross browser rotation
    cross_browser_rotation(o);
}

//////////////////////////////////////////////////////////////////////////////

function initCourse(){

	//scorm.init returns a boolean
	lmsConnected = scorm.init();
	
	
	//If the scorm.init function succeeded...
	if(lmsConnected){
            
//            alert('polaczono z lms api.');
            
	  //Let's get the completion status to see if the course has already been completed
	  var completionstatus = scorm.get("cmi.core.lesson_status");

	  //If the course has already been completed...
	  if(completionstatus == "completed" || completionstatus == "passed"){

		 //...let's display a message and close the browser window
		 handleError("You have already completed this course. You do not need to continue.");

	  }

	  //Now let's get the username from the LMS
	  var learnername = scorm.get("cmi.core.student_name");

	  //If the name was successfully retrieved...
	  if(learnername){  

		 //...let's display the username in a page element named "learnername"
		 //document.getElementById("learnername").innerHTML = learnername; //use the name in the form

	  }

	//If the course couldn't connect to the LMS
	} else {
            if (cfg.scormHandler === "cookie") {
                if (readCookie(cfg.pname) !== null ) {
                    // odczytanie ciastka
                    stringtostatus(readCookie(cfg.pname));
                } else {
                    // tworzenie nowego ciastka
                    createCookie(cfg.pname, statustostring(), 60);
                }
            } if (cfg.scormHandler === "dscorm") {
                if (typeof darkanscorm.data.answers != 'undefined' && darkanscorm.data.answers != '') {
                    quiz = JSON.parse(darkanscorm.data.answers);
                }
                // wczytanie danych z dscorm
                if (typeof darkanscorm.data !== 'undefined' && darkanscorm.data !== '{}' && darkanscorm.data.suspend_data != '' /*&& darkanscorm.uid != 0*/) {
                    stringtostatus(darkanscorm.data.suspend_data);
                }
                
                if (typeof darkanscorm.data === 'undefined' || darkanscorm.data === '{}' || darkanscorm.data.page_time == '' /*&& darkanscorm.uid != 0*/) {
                    for (i = 0; i < all; i++) {
                        currentPageStatus.page_time[i] = 0;
                    }
                } else /*if (darkanscorm.uid != 0)*/ {
                    currentPageStatus.page_time = JSON.parse(darkanscorm.data.page_time);
                }
            }
	}
 
}


function setComplete(){
    
    
//    if (cfg.stat !== 'c') {
//        _gaq.push(['_trackPageview', "/contentshow/" + cfg.pname + "/cmpl"]);
//        mylog("ZALICZAM, poszedl request do GA: " + "/contentshow/" + cfg.pname + "/cmpl");
//    }

    cfg.stat = 'c';
    
    if (cfg.scormHandler === "dscorm") {
        // zaliczam - zapisanie danych do scorm
        darkanscorm.data.status = cfg.stat;
        saveDScorm();
    }
    
    if(lmsConnected){

        var success = scorm.set("cmi.core.lesson_status", "completed");

        scorm.set("cmi.core.score.min", 0);
        scorm.set("cmi.core.score.max", scorm_score_max);
        scorm.set("cmi.core.score.raw", offlineScore);
        scorm.set("cmi.score.scaled", (offlineScore/scorm_score_max) * 100);

        if(success){
            return true;
        }
        else{
            return false;
        }

    } else {
        return false;
    }
 
}

function setFailed() {
    
//    if (cfg.stat !== 'f') {
//        _gaq.push(['_trackPageview', "/contentshow/" + cfg.pname + "/fail"]);
//        mylog("NIE ZALICZAM, poszedl request do GA: " + "/contentshow/" + cfg.pname + "/fail");
//    }
    
    cfg.stat = 'f';
    
    if (cfg.scormHandler === "dscorm") {
        darkanscorm.data.status = cfg.stat;
        saveDScorm();
    }
    
    if(lmsConnected){

        var failed = scorm.set("cmi.core.lesson_status", "failed");

        scorm.set("cmi.core.score.min", 0);
        scorm.set("cmi.core.score.max", scorm_score_max);
        scorm.set("cmi.core.score.raw", offlineScore);
        scorm.set("cmi.score.scaled", (offlineScore/scorm_score_max) * 100);

        if(failed){
            return true;
        }
        else{
            return false;
        }

    } else {
        return false;
    }
}

window.onbeforeunload = function(){
    scorm.set("cmi.core.score.min", 0);
    scorm.set("cmi.core.score.max", scorm_score_max);
    scorm.set("cmi.core.score.raw", offlineScore);
    scorm.set("cmi.score.scaled", (offlineScore/scorm_score_max) * 100);
    
	saveScorm();
	scorm.quit();
};



function saveSuspendData(){
        
        if(zaliczony()){
            if (req.s) {
                var allCompleted = true;
                // petla
//                $.each(mypointstatus, function(key, value) {
//                    $.each(mypointstatus[key], function(key2, value2) {
//                        //if ($.inArray(value2[1], questioncodes) !== -1 ) {
//                            if (value2[3] === 0){
//                                    allCompleted = false;
//                            }
//                        //}
//
//                     });
//                });
                
                if (allCompleted) {
                    if (offlineScore < scorm_score_required){
                        setFailed();
                    } else {
                        if (!setComplete()) {
                            // mylog('I can\'t set course status to complete.');
                        }
                    }
                }

            } else {
                if (!setComplete()) {
                    // mylog('I can\'t set course status to complete.');
                }
            }
        }
        
        scorm.set("cmi.suspend_data", statustostring());
        
        if (cfg.scormHandler === "cookie") {
            createCookie(cfg.pname, statustostring(), 60);
        }
        
        if (cfg.scormHandler === "dscorm") {
            var needs = {
                p: req.p,
                s: req.s,
                e: req.e
            }
            
            darkanscorm.data.suspend_data = statustostring();
            darkanscorm.data.point_status = JSON.stringify(mypointstatus);
            darkanscorm.data.questionsarray = JSON.stringify(questionsarray);
            darkanscorm.data.pages = JSON.stringify(strony);
            darkanscorm.data.needs = JSON.stringify(needs);
            darkanscorm.data.answers = JSON.stringify(quiz);
        }
        
	saveScorm();
}

function create_qq() {

    for (var p in questionsarray) {
        quiz[p] = {
            u: {
                answer: {},
                attempts: 0,
                pass: ''
            }
        };
    }
}

function setLessonLocation(currentPage){
//        alert('setLessonLocation: ' + currentPage);

    if (cfg.scormHandler === "cookie") {
        createCookie(cfg.pname + "_ll", currentPage, 60);
    } else if (cfg.scormHandler === "dscorm") {
        darkanscorm.data.lesson_location = currentPage;
    } else {
        scorm.set("cmi.core.lesson_location", currentPage);
    }
//    mylog('Ustawianie VisitedPage w GA');
//    _gaq.push(['_setCustomVar',
//              1,
//              'VisitedPage',
//              currentPage,
//              1
//    ]);
	
    saveSuspendData();
}

function saveScorm(){
//        alert('SAVING SCORM');
	scorm.save();
}

function saveDScorm() {
//    var scorm_data = {
//        status: cfg.stat,
//        lesson_location: page_order,
//        suspend_data: statustostring()
//    }
    currentPageStatus.start(page_order);
    
    if (typeof darkanscorm === 'object')
        darkanscorm.set(darkanscorm.data);
}

//function getDScorm() {
//    var ret = darkanscorm.get();
//    
//    var data = JSON.parse(ret.data);
//    
//    stringtostatus(data.suspend_data);
//    
//    mylog(data);
//}

function parallax_handler(elem) {
        add_over_animation(elem);
        add_constant_animation(elem);

        var parallax = {  };
        var iframe = $('#insideFrame').contents();
        
        var parallax_obj = eval( "(" + elem.attr('parallax') + ")");

        if (typeof parallax_obj === "object") {

            if (parallax_obj.cursor.on === true || parallax_obj.scroll.on === true) {
                    var ak = elem.attr('actionkey');

                    parallax[ak] = {
                        width: elem.width(),
                        height: elem.height(),
                        top: parseInt(elem.css('top')) - iframe.scrollTop(),
                        left: parseInt(elem.css('left')),
                        last_y: 0,
                        last_x: 0
                    };

            }
        }
            
        

        
        iframe.bind('scroll mousemove', function(e){
            var cont = $(this);
            
            for (var i in parallax) {
                var parallax_obj = eval( "(" + elem.attr('parallax') + ")");
                
                
                var cursor_new_left = null;
                var cursor_new_top = null;
                
                if (parallax_obj.scroll.on === true) {
                    if (parseInt(parallax_obj.scroll.sens) === 0) {
                        parallax_obj.scroll.sens = 10;
                    }
                    
                    var scroll_sens = parseInt(parallax_obj.scroll.sens) * 0.1;
                    
                    cursor_new_top = (parallax[i].top + (cont.scrollTop() * scroll_sens));
                } else {
                    cursor_new_top = parallax[i].top;
                }

                if (parallax_obj.cursor.on === true) {
                    var cursor_sens = (101 - parseInt(parallax_obj.cursor.sens));


                    var x = ((e.pageX - parallax[i].left - (elem.width() / 2) ) / (cursor_sens));
                    var y = ((e.pageY - cursor_new_top - (elem.height() / 2) ) / (cursor_sens));
                    
                    if (isNaN(x) || isNaN(y)) {
                        // to jebac kurwow
                        y = parallax[i].last_y;
                        x = parallax[i].last_x;
                    }
                    if (parallax_obj.cursor.dir === false) {
                        cursor_new_left = parallax[i].left - x;
                        cursor_new_top = cursor_new_top - y;
                    } else {
                        cursor_new_left = parallax[i].left + x;
                        cursor_new_top = cursor_new_top + y;
                    }
                    
                    parallax[i].last_y = y;
                    parallax[i].last_x = x;
                    
                }

                // wyswietlanie 
                if (parallax_obj.cursor.on === true) {
                    if (cursor_new_left !== null) {
                        elem.css({
                            left: cursor_new_left + "px"
                        });
                    }

                }
                elem.css({
                    top: cursor_new_top + "px"
                });
                
                
            }
        });

//        iframe.scroll(function() {
//            var cont = $(this);
//            
//            for (var i in parallax) {
//                var o = cont.find('div[actionkey="'+ i +'"]').first();
//                var parallax_obj = eval( "(" + o.attr('parallax') + ")");
//                if (parallax_obj.scroll.on === true) {
//                    
//                    
//                    var sens = parseInt(parallax_obj.scroll.sens) * 0.01;
//                    
//                    
//                    var newTop = (parallax[i].top + (cont.scrollTop() * sens));
//                    
//                    o.css('top', newTop + 'px');
//                }
//            }
//        });
}

function sprawdz_status() {
    clearAndEnableCheckbox();
        
	$('#insideFrame').contents().find('div[actionkey], a[actionkey]').each(function() {
            
		var point = $(this);
                
                if (point.attr('animation-actionend') != 'none') {
                    point.css('cursor', 'pointer');
                }
                
                if (point.attr('animation-action') == 'all_clicked') {
                    point.css('cursor', 'pointer');
                }
                
                if (point.attr('action') == '18') {
                    var src_video = '';
                    var video_prop = '';
                    var point_key = point.attr('actionkey');
                    var src_videoposter = '';
                    
                    var random = new Date().getTime();
                    
                    switch (point.attr('video-type')) {
                        case '1':
                            // wideo z pliku
                            src_video = 'video/' + point.attr('actionkey') + '/' + point.attr('videofile') + '?r=' + random;
//                            document.getElementById('insideFrame').contentWindow._V_(point_key).dispose();
                            point.html('');

                            if (point.attr('video-autoplay') == 1)
                                video_prop = 'autoplay ';

                            if (point.attr('video-controls') == 1)
                                video_prop += 'controls ';

                            if (point.attr('video-loop') == 1)
                                video_prop += 'loop ';

                            if ($(this).attr('videoposter') != undefined && $(this).attr('videoposter') != '') {
                                src_videoposter = 'poster="video/' + point.attr('actionkey') + '/poster/' + $(this).attr('videoposter') + '"';
                            }

                            point.append('<video id="'+ point.attr('actionkey') + '" class="video-js vjs-default-skin" ' + video_prop + ' preload="auto" ' + src_videoposter + ' width="100%" height="100%"> </video>');
                            document.getElementById('insideFrame').contentWindow._V_(point.attr('actionkey'), {"techOrder": ["flash", "html5", "links"], "src": src_video}, function() {
                                this.src(src_video);
                            });
                            break;
                        
                        case '2':
                            // wideo z youtube
                            src_video = point.attr('videofile');
                            setTimeout(function(){
                                document.getElementById('insideFrame').contentWindow._V_(point_key).dispose();
                                point.html('');

                                if (point.attr('video-autoplay') == 1)
                                    video_prop = 'autoplay ';

                                if (point.attr('video-controls') == 1)
                                    video_prop += 'controls ';

                                if (point.attr('video-loop') == 1)
                                    video_prop += 'loop ';

                                if ($(this).attr('videoposter') != undefined && $(this).attr('videoposter') != '') {
                                    src_videoposter = 'poster="video/' + point.attr('actionkey') + '/poster/' + $(this).attr('videoposter') + '"';
                                }
                                point.append('<video id="'+ point.attr('actionkey') + '" class="video-js vjs-default-skin" ' + video_prop + ' preload="auto" ' + src_videoposter + ' width="100%" height="100%"> </video>');
                                setTimeout(function(){
                                    document.getElementById('insideFrame').contentWindow._V_(point_key, {"techOrder": ["youtube"], "src": src_video, "ytcontrols": false}).ready(function() {
                                        if (point.attr('video-autoplay') == 0)
                                            this.pause();
                                    });
                                }, 1);
                            }, 100);
                            break;
                            
                        case '3':
                            // wideo z vimeo
                           src_video = point.attr('videofile');
                            document.getElementById('insideFrame').contentWindow._V_(point_key).dispose();
                            point.html('');

                            if (point.attr('video-autoplay') == 1)
                                video_prop = 'autoplay ';

                            if (point.attr('video-controls') == 1)
                                video_prop += 'controls ';

                            if (point.attr('video-loop') == 1)
                                video_prop += 'loop ';

                            if ($(this).attr('videoposter') != undefined && $(this).attr('videoposter') != '') {
                                src_videoposter = 'poster="video/' + point.attr('actionkey') + '/poster/' + $(this).attr('videoposter') + '"';
                            }

                            point.append('<video id="'+ point.attr('actionkey') + '" class="video-js vjs-default-skin" ' + video_prop + ' preload="auto" ' + src_videoposter + ' width="100%" height="100%"> </video>');
                            document.getElementById('insideFrame').contentWindow._V_(point_key, {techOrder: ["vimeo"], src: src_video}, function() {
                            });
                            break;
                    }

                }
                
                if (point.attr('action') == '16') {
                    //point.find('img').attr('src', 'images/' + point.attr('actionkey') + '/' + point.attr('imagefile'));
                }
                
                if (point.attr('action') == '9' || point.attr('action') == '10') {
                    //if (view_true == 'true')
                        //point.css('background-image', "url('../../images/" + point.attr('actionkey') + '/' + point.attr('imagefile') + "')");
                        //point.find('img').attr('src', 'images/' + point.attr('actionkey') + '/' + point.attr('imagefile'));
                    //else
                        //point.css('background-image', "url('../../images/" + point.attr('actionkey') + '/' + point.attr('imagefile') + "')");
                    //alert('zmieniam tlo: ' + point.attr('imagefile'));
                }
                if (point.attr('action') == '12' && point.attr('isquestion') == 'false') {
//                    alert('obczajam zwykły SWF;');
                    point.find('object').attr('data', 'swf/' + point.attr('actionkey') + '/' + point.attr('swffile'));
                    point.find('object param[name="movie"]').attr('value', '"swf/' + point.attr('actionkey') + '/' + point.attr('swffile') + '"');
                }

		var i = page - 1;

		j = 0;
		$.each(mypointstatus[i], function(key2, value2) {
                    
                        // cursor pointer dla punktow klikalnych
                        if ((mypointstatus[i][j][0] == point.attr('actionkey')) && (point.attr('action') != 22)) {
                            point.css('cursor', 'pointer');
                        }
                        
			if ((mypointstatus[i][j][3] == 1 || mypointstatus[i][j][3] == 2) && mypointstatus[i][j][0] == point.attr('actionkey')) {
//                            alert('obczajam punkt ' + point.attr('actionkey') + ', jego stan to: ' + mypointstatus[i][j][3] );

                            // jeśli punkt jest ćwiczeniem multiselect HTML5
                            if (point.attr('action') == '22'){
                                
                                point.find('input, a, label').addClass('disabled-btn').prop('disabled', true);
                                
                                if (mypointstatus[i][j][3] == 1){
                                    if (point.attr('fsign') === 'true') {
                                        point.find('.question-header').append('<p class="question-completed">&#x2713;</p>');
                                        
                                        var answers = point.find('.multiple-answer');

                                        var k = 0;
                                        answers.each(function(){
                                                if (questionsarray[point.attr("actionkey")]["answers"][k] == "true"){
                                                    $(this).find('input').prop('checked', true);
                                                }
                                                k++;
                                        });
                                    }
                                }
                                else if (mypointstatus[i][j][3] == 2){
                                    if (point.attr('fsign') === 'true') {
                                        point.find('.question-header').append('<p class="question-failed">&#x2717;</p>');
                                    }

                                    
/* ================== FAOO ====================== */
                                    // var answers = point.find('.multiple-answer');

                                    // var k = 0;
                                    // answers.each(function(){
                                    //         if (questionsarray[point.attr("actionkey")]["answers"][k] == "true"){
                                    //             $(this).find('input').prop('checked', true);
                                    //         }
                                    //         k++;
                                    // });
/* ================== FAOO end ====================== */
                                }
                                
                            }
                            // jeśli punkt jest ćwiczeniem wypelnij luki HTML5
                            if (point.attr('action') == '23'){
                                
                                
                                point.find('input, a, select, .qtext-submit').addClass('disabled-btn').prop('disabled', true);
                                if (mypointstatus[i][j][3] == 1){
                                    if (point.attr('fsign') === 'true') {
                                        point.find('.qtext-header').append('<p class="question-completed">&#x2713;</p>');
                                    }       
                                    
                                    // TODO: cwiczenie jest zaliczone wiec pokaz jego prawidlowe odpowiedzi
//                                    var answers = point.find('.multiple-answer');
//
//                                    var k = 0;
//
//                                    answers.each(function(){
//                                            
//                                            if (questionsarray[point.attr("actionkey")]["answers"][k] == "true"){
//                                                $(this).find('input').prop('checked', true);
//                                            }
//
//                                            k++;
//                                    });
                                    
                                }
                                else if (mypointstatus[i][j][3] == 2){
                                    if (point.attr('fsign') === 'true') {
                                        point.find('.qtext-header').append('<p class="question-failed">&#x2717;</p>');
                                    }
                                }
                                
                            }
                            
                            
                            // jeśli punkt jest ćwiczeniem SWF
                            else if (point.attr('action') == '12' && point.attr('isquestion') == 'true'){
//                                alert('obczajany punkt jest ćwiczeniem SWF, jego wczytany stan to: ' + mypointstatus[i][j][3]);
                            }
                            // każdy inny punkt
                            else
                            {
//                                alert('obczajany punkt jest zwykłym punktem, jego wczytany stan to: ' + mypointstatus[i][j][3]);
                                
                                point.removeClass('inactive-point').addClass('active-point');
                                
                                // border do zaznaczenia
                                if (point.attr('action') == '5')
                                    point.css('border-color', point.attr('bordercolor-active'));
                                
                                if (point.attr('action') == '41' ||
                                    point.attr('action') == '42' ||
                                    point.attr('action') == '43' ||
                                    point.attr('action') == '44'
                                )
                                    point.css('border-color', point.attr('bordercolor-active'));
                            }  
                            
                            
                            
                            // punkt jest zaliczony według informacji ze scorma więc ustawiam punkt na odwiedzony w timeline_tab
                            // ale tylko dla ćwiczen!
                            if (point.hasClass('quiz') || (point.attr('action') == '12' && point.attr('isquestion') == 'true')) {
                                for(var item in timeline_tab[i]){
                                    for (var line in timeline_tab[i][item]){
                                        for (var p in timeline_tab[i][item][line]){
                                            if (point.attr("actionkey") == timeline_tab[i][item][line][0])
                                                timeline_tab[i][item][line][5] = 1;
                                        }
                                    }
                                }
                            }
                            
			}

			j++;
		});
	});
        
//        $('#insideFrame').contents().find('.quiz-multiple-wrapper').each(function() {
//		var myActtualPage = page - 1;
//                var question = $(this);
//
//		j = 0;
//		$.each(mypointstatus[myActtualPage], function(qKey, qValue) {
//                        
//			if ((mypointstatus[myActtualPage][j][3] == 1 || mypointstatus[myActtualPage][j][3] == 2) && mypointstatus[myActtualPage][j][0] == question.attr('actionkey')) {
//				mylog('zaliczone cwiczenie');
//                                question.find('input, a').addClass('disabled-btn').prop('disabled', true);
//                                if (mypointstatus[myActtualPage][j][3] == 1)
//                                    question.find('.question-header').append('<p class="question-completed">&#x2713;</p>');
//                                else if (mypointstatus[myActtualPage][j][3] == 2)
//                                    question.find('.question-header').append('<p class="question-failed">&#x2717;</p>');
//                                
//                                
//                                if (mypointstatus[myActtualPage][j][3] == 1){
//                                    var answers = question.find('.multiple-answer');
//
//                                    var k = 0;
//
//                                    answers.each(function(){
//
//                                            if (questionsarray[question.attr("actionkey")]["answers"][k] == "true"){
//                                                $(this).find('input').prop('checked', true);
//                                            }
//
//                                            k++;
//                                    });
//                                }
//                                
//			}
//
//			j++;
//		});
//	});
	
//	saveSuspendData();
//	saveScorm();
	
}

function statustostring() {
    
        // inicjalizacja obiektu suspend_data do przekazania do scorma
	var status_json = { 
            pages   : [ ],
            draw    : [ ],
            points  : [ ],
            score   : offlineScore,
            stat    : cfg.stat
        };
        
        // zapisujemy wszystkie strony do obiektu status_json.pages jako tablica statusów 1 i 0
	$.each(strony, function(key, value) {
            status_json.pages.push(value[0]);
	});
        
        // strona
	$.each(drawarr, function(page, value) {
            
            //status_json.draw.push(page);
            status_json.draw[page] = {};
            
            // linia
            $.each(value, function(row, value2) {
                status_json.draw[page][row] = [];
                
                // obiekty
                i = 0;
                $.each(value2['objs'], function(obj, value3) {
                    if (value3["isdrawed"] == 1) {
                        status_json.draw[page][row].push(i);
                    }
                    i++;
                });
            });
	});
        
        
        
        // zapisujemy wszystkie statusy punktów do obiektu status_json.points
	$.each(mypointstatus, function(key, value) {
            $.each(mypointstatus[key], function(key2, value2) {
                    /*
                     *  0 - strony
                     *  1 - czy zaliczony (0-nie ruszany, 1-zaliczony, 2-niezaliczony)
                     *  2 - identyfikator punktu na danej stronie, jego kolejnosc
                     *  3 - liczba dostepnych prób tj. attempts (i-infinite, liczba całkowita, n-no attempts)
                     */
                    var obj = [
                        parseInt(key),
                        parseInt(key2),
                        parseInt(value2[3])
                    ];
                    
                    // jesli to jest cwiczenie to zczytaj ilosc dostepnych prob z tablicy
                    var attemptsToJson = 'i';
                    if (value2[0] in questionsarray){
                        // ilosc prob danego cwiczenia
                        attemptsToJson = questionsarray[value2[0]]["attempts"];
                        // dodaj nowa wartosc do obiektu 
                        obj[3] = attemptsToJson;
                    }
                    
                    // dodaj obiekt punktu do status_json.points
                    status_json.points.push(obj);
             });
		 
	});
	return JSON.stringify(status_json);
}

function stringtostatus(status_string) {
        status_string = JSON.parse(status_string);
	
	$.each(strony, function(key, value) {
            strony[key][0] = status_string.pages[key];
	});
        
	$.each(mypointstatus, function(page_id, value) {
            $.each(mypointstatus[page_id], function(point_id, value2) {
                $.each(status_string.points, function(scorm_point_id, scorm_val) {
                    
                    
                    if ( scorm_val[0] == page_id && scorm_val[1] == point_id){
                        
                        mypointstatus[page_id][point_id][3] = scorm_val[2];

                        if (scorm_val[3] != undefined) {
                            var actionkey_p = mypointstatus[page_id][point_id][0];
                            questionsarray[actionkey_p]["attempts"] = scorm_val[3];
                        }
                        
                    }
                });
                    
             });
	});
        
        for (var page in drawarr) {
            for (var draw in drawarr[page]) {
                var i = 0;
                for (var ob in drawarr[page][draw]["objs"]) {
                    if ($.inArray( i, status_string.draw[page][draw] ) !== -1) {
                        drawarr[page][draw]["objs"][ob]["isdrawed"] = 1;
                    }
                    i++;
                }
            }
        }
        cfg.draw = true;
        
        offlineScore = parseInt(status_string.score);
        
        if (typeof status_string.stat !== undefined){
            cfg.stat = status_string.stat;
        }
        
        
}

function zaliczony() {
        if (offlineScore > scorm_score_max) {
            //mylog('Well, well, you have too many points...');
        }
        
	var zaliczony = true;
        
        // sprawdzenie czy wszystkie strony sa odwiedzone
        if (req.p) {
            $.each(strony, function(key, value) {
                    if (value[0] == 0){
                            zaliczony = false;
                            return false;
                    }
            });
            if (zaliczony == false) 
                return false;
        }
        
        // sprawdzenie czy wszystkie punkty sa zaliczone
        if (req.e) {
            $.each(mypointstatus, function(key, value) {
                    $.each(mypointstatus[key], function(key2, value2) {
                            if (value2[3] == 0){
                                    zaliczony = false;
                                    return false;
                            }
                     });
            });
            if (zaliczony == false) 
                return false;
        }
        return true;
}

function sound_control() {
	if ($('#insideFrame').contents().find('#sound').attr('src') == undefined) {
		$('#play').css('opacity', '0.4').css('cursor', 'default');
		$('#pause').css('opacity', '0.4').css('cursor', 'default');
		$('#stop').css('opacity', '0.4').css('cursor', 'default');
	} else {
		$('#play').css('opacity', '1').css('cursor', 'pointer');
		$('#pause').css('opacity', '1').css('cursor', 'pointer');
		$('#stop').css('opacity', '1').css('cursor', 'pointer');
                
                if ( mutepage )
                    $('#insideFrame').contents().find('#sound').get(0).volume = 0;
                else
                    $('#insideFrame').contents().find('#sound').get(0).volume = 1;
	}
}



// te funckcje bindujace byly w iframe load
function unbindNextBtn(){
//	if(isNextBinded){
//                mylog('UNBIND NEXT BTN');
		$('#next').css('opacity', '0.3');
		$("#next").unbind('click', nextScreenFn);   
		isNextBinded = false;
//	}
	
}

function bindNextBtn(){
	if(!isNextBinded){
            if((page_order+1) < all) {
//                mylog('BIND NEXT BTN');
                $('#next').css('opacity', '1');
                $("#next").bind('click', nextScreenFn);
                isNextBinded = true;
            }
	}
	
}

function unbindPrevBtn(){
//	if(isPrevBinded){
//                mylog('UNBIND PREVIOUS BTN');
		$('#previous').css('opacity', '0.3');
		$("#previous").unbind('click', prevScreenFn);   
		isPrevBinded = false;
//	}
	
}

function bindPrevBtn(){
	if(!isPrevBinded){
            if(page_order != 0) {
//                mylog('BIND PREVIOUS BTN');
                $('#previous').css('opacity', '1');
                $("#previous").bind('click', prevScreenFn);
                isPrevBinded = true;
            }
	}
}



//Popup dialog/
function popup(message) {
		
    // get the screen height and width  
    var maskHeight = $(document).height();  
    var maskWidth = $(window).width();

    // calculate the values for center alignment
    var dialogTop =  (maskHeight/3) - ($('#dialog-box').height());  
    var dialogLeft = (maskWidth/2) - ($('#dialog-box').width()/2); 

    // assign values to the overlay and dialog box
    $('#dialog-overlay').css({height:maskHeight, width:maskWidth}).fadeIn();
    $('#dialog-box').css({top:dialogTop, left:dialogLeft}).fadeIn();

    // display the message
    $('#dialog-message').html(message);

}

function loadConfig(){
    
                
    $("#counter").text((page_order+1)+'/'+ all);

    i = 0;

    
    
    strony[0][0] = 1;
    if(lmsConnected){
            if(scorm.get("cmi.suspend_data") != ""){
                    stringtostatus(scorm.get("cmi.suspend_data"));
//                    alert('wczytywanie suspend data: ' + scorm.get("cmi.suspend_data"))
            } else {
//                    alert("suspend data jest pusty");
            }
            
            
    }
			
		
		//complete: function() {
    setTimeout(function() {
//        sprawdz_status();
        //var cancelBtn = lang['PUB_CANCEL'];
        var myCurrectPage = 0;
        
        if (cfg.scormHandler === "cookie") {
            myCurrectPage = parseInt(readCookie(cfg.pname + "_ll"));
        } else if (cfg.scormHandler === "dscorm") {
            myCurrectPage = parseInt(darkanscorm.data.lesson_location);
        } else {
            myCurrectPage = scorm.get("cmi.core.lesson_location");
        }

        if(isNaN(myCurrectPage) || myCurrectPage == 0){
                //alert('Lesson location: ' + myCurrectPage);
        }else{
            if (last_page_position == 1) {
                $('<div />').html( lang['PUB_LASTPAGE'] + (parseInt(myCurrectPage)+1) +')').dialog({
                        resizable: false,
                        title: lang['PUB_LASTPAGE_CONTINUE'],
                        height:240,
                        modal: false,
                        position: { my: "center", at: "center", of: $('#skin') },
                        buttons: {
                                "Ok": function(){
                                        $('#insideFrame').fadeOut(500);
                                        timeout = setTimeout(function(){
    //                                            $('#zoom').removeClass('zoom-out').addClass('zoom-in');
                                                page_order = parseInt(myCurrectPage);
                                                page = strony[myCurrectPage][1];
                                                $("#insideFrame").attr("src", "exported/"+strony[myCurrectPage][1]+"/page.html").one("load", function() {
                                                        $(this).fadeIn(500);
                                                        sprawdz_status();
    //                                                    sound_control();
                                                        setLessonLocation(parseInt(myCurrectPage));
                                                        currentPageStatus.start(page_order);
                                                        
                                                });
                                                $("#counter").text((parseInt(myCurrectPage)+1)+'/'+all);
                                                //strony[page-1][0] = 1;

                                        }, 800);
                                        $( this ).dialog( "close" );
                                }
    //                            ,
    //                            Cancel : function(){
    //                                    $( this ).dialog( "close" );
    //                            }
                        }
                }).parent().addClass('dialog-lastpage');
            } else if (last_page_position == 2) {
                page_order = parseInt(myCurrectPage);
                page = strony[myCurrectPage][1];
                $("#insideFrame").attr("src", "exported/"+strony[myCurrectPage][1]+"/page.html").one("load", function() {
                        $(this).fadeIn(500);
                        sprawdz_status();
//                                                    sound_control();
                        setLessonLocation(parseInt(myCurrectPage));
                        currentPageStatus.start(page_order);
                        
                });
                $("#counter").text((parseInt(myCurrectPage)+1)+'/'+all);
            }
        }
    }, 500);
}

function getURLParam()
{

    url =  window.location.search.substring(0);

    var result = {};
                var searchIndex = url.indexOf("?");
                if (searchIndex == -1 ) return result;
    var sPageURL = url.substring(searchIndex +1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++)
    {    	
        var sParameterName = sURLVariables[i].split('=');      
        result[sParameterName[0]] = sParameterName[1];
    }
    return result;
}


function handle_advance_action(point) {
    mylog('handle_advance_action()');
    var option = 'none';
    if (point.attr('animation-actionend') != undefined && point.attr('animation-actionend') != 'none')
        option = point.attr('animation-actionend');
    else
        option = 'none';
    
    
    var wait_time = 1000;
    
    if(point.attr('animation-out') == 'none')
        wait_time = 1;
    
    
    setTimeout(function() {
        switch (option) {
            case 'none' :
                break;
            case 'nextpage' :
                if ((page_order+1) != all){
                    $('#insideFrame').fadeOut(500);
                    timeout = setTimeout(function(){
    //                    page_order++;
    //                    page = strony[page_order][1];

                        // strony[page_order][0] = 1;
                        //$('#zoom').removeClass('zoom-out').addClass('zoom-in');
                        var view_true_dir;
                        if (view_true == 'true')
                            view_true_dir = '_view';
                        else
                            view_true_dir = '';
                        if (my_attr == undefined || my_attr == '')
                            my_attr = '';

                        $("#insideFrame").attr("src", "exported" + view_true_dir + "/"+page+"/page.html" + my_attr).one("load", function() {
                            $(this).fadeIn(500);
                            $('#pagename').text(nazwa_strony[page-1]);
//                            sound_control();
                            sprawdz_status();
                            setLessonLocation(page_order);
                            currentPageStatus.start(page_order);
                        });
                        $("#counter").text((page_order+1)+'/'+all);
//                        if(zaliczony()){
//                            setComplete();
//                        }
                    }, 500, page_order++, page = strony[page_order][1]);
                }
                break;
            case 'prevpage' :
                if ((page_order+1) != 1){
                    $('#insideFrame').fadeOut(500);
                    timeout = setTimeout(function(){
    //                    page_order--;
    //                    page = strony[page_order][1];

    //                    $('#zoom').removeClass('zoom-out').addClass('zoom-in');
                        var view_true_dir;
                        if (view_true == 'true')
                            view_true_dir = '_view';
                        else
                            view_true_dir = '';

                        if (my_attr == undefined || my_attr == '')
                            my_attr = '';

                        $("#insideFrame").attr("src", "exported" + view_true_dir + "/"+page+"/page.html" + my_attr).one("load", function() {
                            $(this).fadeIn(500);
                            $('#pagename').text(nazwa_strony[page-1]);
                            sprawdz_status();
//                            sound_control();
                            setLessonLocation(page_order);
                            currentPageStatus.start(page_order);
                        });
                        $("#counter").text((page_order+1)+'/'+all);
                        // strony[page_order][0] = 1;
//                        if(zaliczony()){
//                            setComplete();
//                        }
                    }, 500, page_order--, page = strony[page_order][1]);
                } 
                break;
            case 'gotoline':
                var scrolltime = parseInt(point.attr("actionend-scrolltime")) * 1000;
                $('#insideFrame').contents().find("html, body").animate({ scrollTop: parseInt(point.attr("topval")) }, { duration: scrolltime, easing: 'swing' });
                break;
            // case 'checkquestion':
            //     var check_timeline_row = parseInt(point.attr('timeline-row'));
            //     for (var par in timeline_tab[page-1][check_timeline_row]) {
            //         console.log('aaa');
            //         for (var pp in mypointstatus[page-1]) {
            //             if (mypointstatus[page-1][pp][0] == timeline_tab[page-1][check_timeline_row][par][0]) {
            //                 if (mypointstatus[page-1][pp][1] == 22) {
            //                     console.log('znaleziono jakies cwiczenie: ' + mypointstatus[page-1][pp][1]);
            //                     var qq = $('#insideFrame').contents().find('.quiz-multiple-wrapper[actionkey="' + mypointstatus[page-1][pp][0] + '"]');
            //                     var ret = checkAnswers(qq);
            //                 }
            //                 if (mypointstatus[page-1][pp][1] == 23) {

            //                     var qq = $('#insideFrame').contents().find('.qtext[actionkey="' + mypointstatus[page-1][pp][0] + '"]');
            //                     var ret = Qtext.checkAnswers(qq);
            //                 }
            //             }
            //         }
            //     }
            //     break;
            default:
                mylog('handle_advance_action() - defalult');
                // szukanie strony po ide strony
                $.each(strony, function(key, value) {
                    mylog('key: ' + key + ', value: ' + value[1]);
                    if (strony[key][1] == parseInt(option)) {
                        //page = parseInt(key) + 1;
                        page_order = parseInt(key);
                        page = strony[page_order][1];
                    }

                });
                $('#insideFrame').fadeOut(500);
                timeout = setTimeout(function(){
    //                $('#zoom').removeClass('zoom-out').addClass('zoom-in');
                    var view_true_dir;
                    if (view_true == 'true')
                        view_true_dir = '_view';
                    else
                        view_true_dir = '';
                    if (my_attr == undefined || my_attr == '')
                        my_attr = '';

                    $("#insideFrame").attr("src", "exported" + view_true_dir + "/"+page+"/page.html" + my_attr).one("load", function() {
                        $(this).fadeIn(500);
                        $('#pagename').text(nazwa_strony[page-1]);
                        sprawdz_status();
//                        sound_control();
                        setLessonLocation(page_order);
                        currentPageStatus.start(page_order);
                    });
                    $("#counter").text((page_order+1)+'/'+all);
                    // strony[page_order][0] = 1;

//                    if(zaliczony()){
//                            setComplete();
//                    }

                }, 500);
        }
    }, wait_time);
}

function loadFrameFunction(){
        mylog('loadFrameFunction()');
        
	var iframe = $('#insideFrame').contents();
                
	var isiPad = navigator.userAgent.match(/iPad/i) != null;
	
	if(isiPad){
		$('#screen').css('overflow-y', 'auto');
	}
				
	//swipe handler
	iframe.touchwipe({
		wipeLeft: nextScreenFn,
		wipeRight: prevScreenFn,
		preventDefaultEvents: false
	});

	
	$('.div-point, .div-point-resizable, .div-point-image, .feedback-button', iframe).mousedown(function() {
		var point = $(this);
                setTimeout(function() {
                    if(point.hasClass('feedback-button')) {
                        if (point.attr('actionkey') != undefined) {
                            handle_advance_action(iframe.find('#divimg div[actionkey="' + point.attr('actionkey') + '"]'));

                        }
                    } else {
                        handle_advance_action(point);
                    }
                }, 50);
		                                                        

		i = 0;
		$.each(mypointstatus, function(key, value) {
			j = 0;
			$.each(mypointstatus[key], function(key2, value2) {
                                
					if (point.attr('actionkey') == mypointstatus[key][j][0]) {
						if(page == (parseInt(key) + 1)){
                                                    if (mypointstatus[key][j][3] == 0) {
                                                        
                                                        mypointstatus[key][j][3] = 1;
                                                        offlineScore += parseInt(mypointstatus[key][j][2]);
                                                        
                                                        // odswiez quiz results diva
                                                        $('#insideFrame').contents().find('.quiz-results-wrapper').each(function(){
                                                            populateQuizResultDivs($(this));
                                                        });
                                                        
                                                        saveSuspendData();  
                                                    }
                                                }
                                                
                                                
                                                point.removeClass('inactive-point').addClass('active-point');
                                                if (point.attr('action') == '5')
                                                    point.css('border-color', point.attr('bordercolor-active'));
                                                
                                                if (point.attr('action') == '41' ||
                                                    point.attr('action') == '42' ||
                                                    point.attr('action') == '43' ||
                                                    point.attr('action') == '44'
                                                )
                                                    point.css('border-color', point.attr('bordercolor-active'));
//                                                saveSuspendData();
					}
					j++;
			 });
			 i++;
		});
		
//                if(point.hasClass('feedback-button')) {
//                    if (point.attr('actionkey') != undefined) {
//                        
//                        mylog('wlaczanie handle_advance_action(iframe)');
//                        handle_advance_action(iframe.find('#divimg div[actionkey="' + point.attr('actionkey') + '"]'));
//                        
//                    }
//                } else {
//                    mylog('wlaczanie handle_advance_action(point)');
//                    handle_advance_action(point);
//                }
		
		
	});
        
        
        // jesli strona jest wyciszona nie uruchamiaj nowych 
        $('#insideFrame').contents().find('.sm2_button').click(function(){
            var sm = window.frames[0].window.soundManager;
            if (mutepage)
                setTimeout(function() { sm.muteAll(); }, 20);

        });
        

        check_and_show_attempts();
}

var timeline_transition = {};
var timeline_row = 0;
var timeline_row_completed = false;

var animation_timeout_1;
var animation_timeout_2;
var animation_timeout_3;
var animation_timeout_4;

function load_timeline_transition() {
    delete timeline_transition;
    timeline_transition = {};
    
    var i = 0;
    
    // sprawdzenie czy znajduja sie punkty na danej stronie
    //if (timeline_tab[page-1][0] && timeline_tab[page-1][0][0]) {
    if (timeline_tab[page-1] && timeline_tab[page-1][0] && timeline_tab[page-1][0][0]) {
        $.each(timeline_tab[page-1], function(key, value) {
            timeline_transition[i] = value[0][4];
            if (is_ie7 === 1) {
                $.each(value, function(key2, value2) {
                    timeline_tab[page-1][key][key2][2] = value2[9];
                    timeline_tab[page-1][key][key2][3] = value2[10];
                });
            }
            i++;
        });
    }
    
    
}

function check_timeline_row(row) {
    var return_val = 1;
    
    // jeśli chcemy odczytać nieistniejący row to nie wykonuj kodu wcale
    if(timeline_tab[page-1][row] != undefined){
        
        $.each(timeline_tab[page-1][row], function(key, value) {
            if (value[5] == "0")
                return_val = 0;
        });
        
    } else {
        return_val = 0;
    }
    return return_val;
}

function clear_visited_status(page) {
    if (timeline_tab[page-1] && timeline_tab[page-1][0] && timeline_tab[page-1][0][0]) {
        $.each(timeline_tab[page-1], function(key, value) {
                $.each(value, function(key2, value2) {
                    timeline_tab[page-1][key][key2][5] = 0;
                });
            i++;
        });
    }
}

function last_element_on_page(page) {
    var last_elem = "";
    
    // jeśli chcemy odczytać nieistniejący row to nie wykonuj kodu wcale
    if(timeline_tab[page-1] != undefined){
        
        $.each(timeline_tab[page-1], function(key, value) {
            $.each(timeline_tab[page-1][key], function(rowkey, rowvalue) {
                last_elem = rowvalue[0];
            });
        });
        
    } else {
        last_elem = "";
    }
    return last_elem;
}

function lock_skin_navigation() {
    var toc = $('#toc');
    
    if (strony[page_order][0] === 0) {
        // unbindPrevBtn();
        unbindNextBtn();
        
        toc.css("opacity", ".2");
    }
}

function lock_page_scrollbar() {
    $('#insideFrame').contents().find("html").css('overflow', 'hidden');
}
function unlock_page_scrollbar() {
    $('#insideFrame').contents().find("html").css({
        'overflow-y': 'auto',
        'overflow-x': 'hidden'
    });
}

function unlock_skin_navigation() {
    
    var toc = $('#toc');
    
    bindNextBtn();
    // bindPrevBtn();

    strony[page_order][0] = 1;
    
    toc.css("opacity", "1");
    
    
}

function draw_elements() {
    
    if (!cfg.draw) {
        // losuj niewylosowane elemnty
        for (var page in drawarr) {

            for (var draw in drawarr[page]) {
                var draw_num = drawarr[page][draw]["num"];
                var draw_max = Object.keys(drawarr[page][draw]["objs"]).length;

                var draw_array = [];

                // wypelnij tablice do losowania
                for (var ob in drawarr[page][draw]["objs"]) {
                    draw_array.push(ob);
                }

                // wylosuj obiekty do wyswietlenia
                for (var i = 0; i < draw_num; i++) {
                    var random = Math.floor(Math.random() * (draw_array.push()));
                    drawarr[page][draw]["objs"][draw_array[random]]["isdrawed"] = 1;
                    draw_array.splice(random, 1);
                }
            }
        }
        saveSuspendData();
    }
    
    
}

function handle_end_page_actions() {
    if( strony[page_order][2] == true ) {
        
        if (strony[page_order][3] !== "none") {
            setTimeout(function() {
                unlock_skin_navigation();
            }, 1300);
        } else {
            unlock_skin_navigation();
        }
    }
    
    fire_page_end_action();
}

function fire_page_end_action() {
    
    if ( strony[page_order][3] !== "none" ) {
        var obj_to_pass = $('<div animation-actionend="'+ strony[page_order][3] +'"></div>');
        handle_advance_action(obj_to_pass);
    }
}

function scroll_page(obj, time) {
    $('#insideFrame').contents().find("html, body").animate({ scrollTop: parseInt(obj.attr("topval")) }, { duration: time*1000, easing: 'swing' });

    if(obj.attr('adv') == 'off') {
        $('#insideFrame').contents().find("html").css('overflow', 'hidden');
    } else if(obj.attr('adv') == 'on') {
        $('#insideFrame').contents().find("html").css('overflow', 'auto');
    }
}

function handle_animations(option, page_last_animation) {
    if (page_last_animation == page) {
        switch (option) {
            case 'no_action':
                 $.each(timeline_tab[page-1][timeline_row], function (key, index) {
                    if($('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').hasClass('quiz-results-wrapper'))
                       populateQuizResultDivs($('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]'));
                   
                   
                     $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').css('display', 'block');
                     index[5] = 1;
                 });
                timeline_row++;
                
                if (last_element_on_page(page) === index[0]){
                    handle_end_page_actions();
                }
                handle_animations(timeline_transition[timeline_row], page);
                break;

            case 'all_clicked':

                var i = 0;
                var time = parseFloat(timeline_tab[page-1][timeline_row][0][1]);
                
                var delaytime = parseFloat(timeline_tab[page-1][timeline_row][0][7]);
                    animation_timeout_1 = setTimeout(function() {
                        if (page_last_animation == page && timeline_tab[page-1][timeline_row] != undefined) {
                            $.each(timeline_tab[page-1][timeline_row], function (key, index) {
                                //piopio
                                var currObj = $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]');

                                // dodanie do punktu zaliczajacego cwiczenia timeline_row
                                if (currObj.attr('animation-actionend') == 'checkquestion') {
                                    currObj.attr('timeline-row', timeline_row);
                                }
                                
                                fire_before_enter(currObj);

                                var drawLine = parseInt(currObj.attr('animation-order'));
                                
                                // jesli aktualny obiekt ma byc losowany to wykonuj
                                if (
                                    typeof drawarr[page-1] === 'object' &&
                                    typeof drawarr[page-1][drawLine] === 'object' &&
                                    typeof drawarr[page-1][drawLine]["objs"][index[0]] === 'object' &&
                                    drawarr[page-1][drawLine]["objs"][index[0]]["isdrawed"] == 0
                                ) 
                                {
                                    if((Object.keys(timeline_tab[page-1][timeline_row]).length -1) == key){
                                        timeline_row++;
                                        handle_animations(timeline_transition[timeline_row], page);
                                    }
                                      
                                // obiekt jest poza losowaniami więc wykonuj normalny kod animacji
                                } else {
                                    if(currObj.hasClass('div-point-scrollerarea')){
                                    scroll_page(currObj, time);
                                }
                                if(currObj.hasClass('quiz-results-wrapper'))
                                    populateQuizResultDivs(currObj);
                                
                                
                                if(index[5] != 1 || index[3] == 'none'){
                                        if (index[2].split('-')[0] != 'js') {
                                            $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').css('display', 'block').addClass('animated').addClass(index[2]);
                                        } else {
                                            //$('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').show(index[2].split('-')[1], 1300);
                                            $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').show(index[2].split('-')[1], { direction: index[2].split('-')[2] },  '', 1300);
                                        }
                                        animation_timeout_2 = setTimeout(function() {
                                            $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').css('display', 'block').removeClass(index[2]);
                                            parallax_handler(currObj);
                                        }, 1300);
                                }
                                
                                if (index[8] !== '') {
                                    $('#insideFrame').contents().find('#point-sound').attr('src', 'sounds/' + index[0] + '/' + index[8]);
                                    $('#insideFrame').contents().find('#point-sound').get(0).play();
                                }
                                
                                    $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').one('mousedown', function() {
                                        if (index[5] != 1) {
                                            if ($(this).hasClass('quiz')) {
                                                $('#insideFrame').contents().find('.feedback-button').mouseup(function(){
                                                    if ($(this).parent().find('.feedback-avatar').hasClass('feedback-avatar-good')){
                                                        
                                                        index[5] = 1;
                                                        
                                                        if (check_timeline_row(timeline_row)) {
                                                            $.each(timeline_tab[page-1][timeline_row], function (key, index) {
                                                                if (index[3] != 'none') {
                                                                    // jesli obiekt ma animation-constant to wylacz ta animacje w animacji wyjscia
                                                                    var oo = $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]');
                                                                    if (oo.attr('animation-constant') !== 'none') {
                                                                        oo.removeClass(oo.attr('animation-constant'));
                                                                    }
                                                                    if (index[3] == 'off') {
                                                                        $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]').hide();
                                                                    } else if (index[3].split('-')[0] != 'js') {
                                                                        $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]').addClass(index[3]);
                                                                    } else {
                                                                        $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]').hide(index[3].split('-')[1], { direction: index[2].split('-')[2] },  '', 1300);
                                                                    }
                                                                }
                                                            });

                                                            if (last_element_on_page(page) === index[0]){
                                                                handle_end_page_actions();
                                                            }
                                                            timeline_row++;
                                                            handle_animations(timeline_transition[timeline_row], page);
                                                            $(this).off('mousedown');
                                                        }
                                                    } else if($(this).parent().find('.feedback-avatar').hasClass('feedback-avatar-bad')) {
                                                        
                                                        var attempts = questionsarray[index[0]]['attempts'];
                                                        if (attempts == "n"){
                                                            index[5] = 1;
                                                            if (check_timeline_row(timeline_row)) {
                                                                $.each(timeline_tab[page-1][timeline_row], function (key, index) {
                                                                    if (index[3] != 'none') {
                                                                        // jesli obiekt ma animation-constant to wylacz ta animacje w animacji wyjscia
                                                                        var oo = $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]');
                                                                        if (oo.attr('animation-constant') !== 'none') {
                                                                            oo.removeClass(oo.attr('animation-constant'));
                                                                        }
                                                                        if (index[3] == 'off') {
                                                                            $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]').hide();
                                                                        } else if (index[3].split('-')[0] != 'js') {
                                                                            $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]').addClass(index[3]);
                                                                        } else {
                                                                            $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]').hide(index[3].split('-')[1], { direction: index[2].split('-')[2] },  '', 1300);
                                                                        }
                                                                    }
                                                                });
                                                                if (last_element_on_page(page) === index[0]){
                                                                    handle_end_page_actions();
                                                                }
                                                                timeline_row++;
                                                                handle_animations(timeline_transition[timeline_row], page);
                                                                $(this).off('mousedown');
                                                            }
                                                        }
                                                    }
                                                });
                                            } else if ($(this).hasClass('div-point-swf')) {
                                                
                                            }
                                            else 
                                            {
                                                index[5] = 1;

                                                if (page_last_animation == page) {
                                                    if (check_timeline_row(timeline_row)) {
                                                        $.each(timeline_tab[page-1][timeline_row], function (key, index) {
                                                            if (index[3] != 'none') {
                                                                // jesli obiekt ma animation-constant to wylacz ta animacje w animacji wyjscia
                                                                var oo = $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]');
                                                                if (oo.attr('animation-constant') !== 'none') {
                                                                    oo.removeClass(oo.attr('animation-constant'));
                                                                }
                                                                if (index[3] == 'off') {
                                                                    $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').hide();
                                                                } else if (index[3].split('-')[0] != 'js') {
                                                                    $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').addClass(index[3]);
                                                                } else {
                                                                    $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').hide(index[3].split('-')[1], { direction: index[2].split('-')[2] },  '', 1300);
                                                                }
                                                            }
                                                        });
                                                        if (last_element_on_page(page) === index[0]){
                                                            handle_end_page_actions();
                                                        }
                                                        timeline_row++;
                                                        handle_animations(timeline_transition[timeline_row], page);
                                                    }
                                                }
                                            }
                                        } 
                                        

                                        
                                    });
                                    // jesli to jest ostatni element w linii to sprawdz czy wszystkie punkty sa zaliczone i jedz dalej z animacjami
                                    
                                    if (index[5] == 1) {
                                        if (last_element_on_page(page) === index[0]){
                                            handle_end_page_actions();
                                        }
                                    }
                                    
                                    var lastElement = 0;
                                    for( var prop in timeline_tab[page-1][timeline_row]){
                                        if(timeline_tab[page-1][timeline_row].hasOwnProperty(prop))
                                            lastElement++;
                                    }
                                    
                                    if((lastElement - 1) == key){
                                        if (check_timeline_row(timeline_row)) {
                                            timeline_row++;
                                            handle_animations(timeline_transition[timeline_row], page);
                                        }
                                    }
                                    //Object.keys(nazwa_strony).length
                                }


                                
                                
                            });
                        }
                    }, delaytime * 1000);
                break;
                
                
                
            case 'all_passed':

                var i = 0;
                var time = parseFloat(timeline_tab[page-1][timeline_row][0][1]);
                var delaytime = parseFloat(timeline_tab[page-1][timeline_row][0][7]);
                // opoznienie gdy czas opoznienia linii ustawiony jest na 0, potrzebne bo dla 0 nie dzialaja animacje
//                if (delaytime == 0)
//                    delaytime = 0.5;
                
                
                    animation_timeout_1 = setTimeout(function() {
                        if (page_last_animation == page && timeline_tab[page-1][timeline_row] != undefined) {
                            $.each(timeline_tab[page-1][timeline_row], function (key, index) {
                                //piopio                                    
                                var currObj = $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]');
                                
                                fire_before_enter(currObj);

                                // dodanie do punktu zaliczajacego cwiczenia timeline_row
                                if (currObj.attr('animation-actionend') == 'checkquestion') {
                                    currObj.attr('timeline-row', timeline_row);
                                }


                                var drawLine = parseInt(currObj.attr('animation-order'));
                                // jesli aktualny obiekt ma byc losowany to wykonuj
                                if (
                                    typeof drawarr[page-1] === 'object' &&
                                    typeof drawarr[page-1][drawLine] === 'object' &&
                                    typeof drawarr[page-1][drawLine]["objs"][index[0]] === 'object' &&
                                    drawarr[page-1][drawLine]["objs"][index[0]]["isdrawed"] == 0
                                ) 
                                {
                                    if((Object.keys(timeline_tab[page-1][timeline_row]).length -1) == key){
                                        timeline_row++;
                                        handle_animations(timeline_transition[timeline_row], page);
                                    }
                                      
                                // obiekt jest poza losowaniami więc wykonuj normalny kod animacji
                                } else {
                                if(currObj.hasClass('div-point-scrollerarea')){
                                    scroll_page(currObj, time);
                                }
                                if(currObj.hasClass('quiz-results-wrapper'))
                                    populateQuizResultDivs(currObj);
                                
                                


                                        if (index[2].split('-')[0] != 'js') {
                                            $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').css('display', 'block').addClass('animated').addClass(index[2]);
                                        } else {
                                            //$('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').show(index[2].split('-')[1], 1300);
                                            $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').show(index[2].split('-')[1], { direction: index[2].split('-')[2] },  '', 1300);
                                        }
                                        animation_timeout_2 = setTimeout(function() {
                                            $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').css('display', 'block').removeClass(index[2]);
                                            parallax_handler(currObj);
                                        }, 1300);
                                
                                if (index[8] !== '') {
                                    $('#insideFrame').contents().find('#point-sound').attr('src', 'sounds/' + index[0] + '/' + index[8]);
                                    $('#insideFrame').contents().find('#point-sound').get(0).play();
                                }
                                var go_through = true;
                                for ( var o in mypointstatus[page-1] ) {
                                    if(mypointstatus[page-1][o][0] == index[0] && index[5] == 0){
                                        go_through = false;
                                    }
                                        
                                }
                                
                                if (go_through){
                                    index[5] = 1;
                                    animation_timeout_3 = setTimeout(function() {
                                        

                                        var lastElement = 0;
                                        for( var prop in timeline_tab[page-1][timeline_row]){
                                            if(timeline_tab[page-1][timeline_row].hasOwnProperty(prop))
                                                lastElement++;
                                        }
                                        if((lastElement - 1) == key){
                                            if (check_timeline_row(timeline_row)) {
                                                
                                                $.each(timeline_tab[page-1][timeline_row], function (insidekey, insideindex) {
                                                    if (insideindex[3] != 'none'){
                                                        // jesli obiekt ma animation-constant to wylacz ta animacje w animacji wyjscia
                                                        var oo = $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]');
                                                        if (oo.attr('animation-constant') !== 'none') {
                                                            oo.removeClass(oo.attr('animation-constant'));
                                                        }
                                                        if (insideindex[3].split('-')[0] != 'js') {
                                                            $('#insideFrame').contents().find('*[actionkey="'+insideindex[0]+'"]').addClass(insideindex[3]);
                                                        } else {
                                                            $('#insideFrame').contents().find('*[actionkey="'+insideindex[0]+'"]').hide(insideindex[3].split('-')[1], { direction: insideindex[2].split('-')[2] },  '', 1300);
                                                            //$('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').hide('puff');
                                                        }
                                                    }
                                                });
                                                if (last_element_on_page(page) === index[0]){
                                                    handle_end_page_actions();
                                                }
                                                timeline_row++;
                                                handle_animations(timeline_transition[timeline_row], page);
                                            }
                                        }
                                    }, time * 1000);
                                }
                                else {
                                
                                    $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').one('mousedown', function() {
                                        if (index[5] != 1) {
                                            if ($(this).hasClass('quiz')) {
                                                $('#insideFrame').contents().find('.feedback-button').mouseup(function(){
                                                    if ($(this).parent().find('.feedback-avatar').hasClass('feedback-avatar-good')){
                                                        
                                                        index[5] = 1;
                                                        
                                                        if (check_timeline_row(timeline_row)) {
                                                            $.each(timeline_tab[page-1][timeline_row], function (key, index) {
                                                                if (index[3] != 'none') {
                                                                    // jesli obiekt ma animation-constant to wylacz ta animacje w animacji wyjscia
                                                                    var oo = $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]');
                                                                    if (oo.attr('animation-constant') !== 'none') {
                                                                        oo.removeClass(oo.attr('animation-constant'));
                                                                    }
                                                                    if (index[3] == 'off') {
                                                                        $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]').hide();
                                                                    } else if (index[3].split('-')[0] != 'js') {
                                                                        $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]').addClass(index[3]);
                                                                    } else {
                                                                        $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]').hide(index[3].split('-')[1], { direction: index[2].split('-')[2] },  '', 1300);
                                                                    }
                                                                }
                                                            });
                                                            if (last_element_on_page(page) === index[0]){
                                                                handle_end_page_actions();
                                                            }
                                                            timeline_row++;
                                                            handle_animations(timeline_transition[timeline_row], page);
                                                            $(this).off('mousedown');
                                                        }
                                                    } else if($(this).parent().find('.feedback-avatar').hasClass('feedback-avatar-bad')) {
                                                        
                                                        var attempts = questionsarray[index[0]]['attempts'];
                                                        if (attempts == "n"){
                                                            index[5] = 1;
                                                            if (check_timeline_row(timeline_row)) {
                                                                $.each(timeline_tab[page-1][timeline_row], function (key, index) {
                                                                    if (index[3] != 'none') {
                                                                        // jesli obiekt ma animation-constant to wylacz ta animacje w animacji wyjscia
                                                                        var oo = $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]');
                                                                        if (oo.attr('animation-constant') !== 'none') {
                                                                            oo.removeClass(oo.attr('animation-constant'));
                                                                        }
                                                                        if (index[3] == 'off') {
                                                                            $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]').hide();
                                                                        } else if (index[3].split('-')[0] != 'js') {
                                                                            $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]').addClass(index[3]);
                                                                        } else {
                                                                            $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]').hide(index[3].split('-')[1], { direction: index[2].split('-')[2] },  '', 1300);
                                                                        }
                                                                    }
                                                                });
                                                                if (last_element_on_page(page) === index[0]){
                                                                    handle_end_page_actions();
                                                                }
                                                                timeline_row++;
                                                                handle_animations(timeline_transition[timeline_row], page);
                                                                $(this).off('mousedown');
                                                            }
                                                        }
                                                    }
                                                });
                                            } else if ($(this).hasClass('div-point-swf')) {
                                                
                                            }
                                            else 
                                            {
                                                index[5] = 1;

                                                if (page_last_animation == page) {
                                                    if (check_timeline_row(timeline_row)) {
                                                        $.each(timeline_tab[page-1][timeline_row], function (key, index) {
                                                            if (index[3] != 'none') {
                                                                // jesli obiekt ma animation-constant to wylacz ta animacje w animacji wyjscia
                                                                var oo = $('#insideFrame').contents().find('div[actionkey="'+index[0]+'"]');
                                                                if (oo.attr('animation-constant') !== 'none') {
                                                                    oo.removeClass(oo.attr('animation-constant'));
                                                                }
                                                                if (index[3] == 'off') {
                                                                    $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').hide();
                                                                } else if (index[3].split('-')[0] != 'js') {
                                                                    $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').addClass(index[3]);
                                                                } else {
                                                                    $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]').hide(index[3].split('-')[1], { direction: index[2].split('-')[2] },  '', 1300);
                                                                }
                                                            }
                                                        });
                                                        if (last_element_on_page(page) === index[0]){
                                                            handle_end_page_actions();
                                                        }
                                                        timeline_row++;
                                                        handle_animations(timeline_transition[timeline_row], page);
                                                    }
                                                }
                                            }
                                        }
                                        
                                    });
                                    
                                    // jesli to jest ostatni element w linii to sprawdz czy wszystkie punkty sa zaliczone i jedz dalej z animacjami

                                    
                                    //Object.keys(nazwa_strony).length
                                    if((Object.keys(timeline_tab[page-1][timeline_row]).length -1) == key){
                                        if (check_timeline_row(timeline_row)) {
                                            timeline_row++;
                                            handle_animations(timeline_transition[timeline_row], page);
                                        }
                                    }
                                    
                                    }
                                    
                                }

                                

                            });
                        }
                    }, delaytime * 1000);
                break;
            
            
            

            case 'after_time':
                var i = 0;
//                var time = parseFloat(timeline_tab[page-1][timeline_row][0][1]);
                var delaytime = parseFloat(timeline_tab[page-1][timeline_row][0][7]);
//                if (delaytime == 0)
//                    delaytime = 0.5;
                var time_begin = 0;
                var last_element_timeout = {
                    actionkey: null,
                    time: 0
                };
                if (timeline_row == 0)
                    time_begin = time * 1000;
                
                    animation_timeout_1 =  setTimeout(function() {  // opoznienie calej linii
                        if (page_last_animation == page) {
                            $.each(timeline_tab[page-1][timeline_row], function (key, index) {
                                var currObj = $('#insideFrame').contents().find('*[actionkey="'+index[0]+'"]');
                                
                                fire_before_enter(currObj);
                                
                                var drawLine = parseInt(currObj.attr('animation-order'));
                                
                                // jesli aktualny obiekt ma byc losowany to wykonuj
                                if (
                                    typeof drawarr[page-1] === 'object' &&
                                    typeof drawarr[page-1][drawLine] === 'object' &&
                                    typeof drawarr[page-1][drawLine]["objs"][index[0]] === 'object' &&
                                    drawarr[page-1][drawLine]["objs"][index[0]]["isdrawed"] == 0
                                ) 
                                {
                                    if((Object.keys(timeline_tab[page-1][timeline_row]).length -1) == key){
                                        timeline_row++;
                                        handle_animations(timeline_transition[timeline_row], page);
                                    }
                                      
                                // obiekt jest poza losowaniami więc wykonuj normalny kod animacji
                                } else {
                                    var time = parseFloat(index[1]);
                                
                                    // obsluga scrollera
                                    if(currObj.hasClass('div-point-scrollerarea')){
                                        scroll_page(currObj, time);
                                    }

                                    // uzupelnienie danych do quiz results
                                    if(currObj.hasClass('quiz-results-wrapper'))
                                        populateQuizResultDivs(currObj);

                                    // ANIMACJA WEJSCIA
                                    if (index[2] !== 'none') {
                                        if (index[2].split('-')[0] === 'js') {
                                            // js
                                            currObj.show(index[2].split('-')[1], { direction: index[2].split('-')[2] }, '', 1300);
                                        } else {
                                            // css3
                                            currObj.css('display', 'block').addClass('animated').addClass(index[2]);
                                        }
                                        // ustaw element na odwiedzony w timeline_tab
                                        index[5] = 1;

                                        // usuniecie klasy animacji wejscia
                                        animation_timeout_2 = setTimeout(function() {
                                            currObj.css('display', 'block').removeClass(index[2]);
                                            parallax_handler(currObj);
                                        }, 1300);
                                    } else {
                                        currObj.css('display', 'block').addClass('animated');
                                        parallax_handler(currObj);
                                        index[5] = 1;
                                    }

                                    // jesli punkt ma dzwiek to zaczyna grac
                                    if (index[8] !== '') {
                                        $('#insideFrame').contents().find('#point-sound').attr('src', 'sounds/' + index[0] + '/' + index[8]);
                                        $('#insideFrame').contents().find('#point-sound').get(0).play();
                                    }

                                    // ANIMACJA WYJSCIA


                                    // sprawdzanie najwiekszego timeouta punktu w linii
                                    if (last_element_timeout.actionkey === null) {
                                        last_element_timeout.actionkey = index[0];
                                        last_element_timeout.time = time;
                                    } else {
                                        if (last_element_timeout.time < time) {
                                            last_element_timeout.actionkey = index[0];
                                            last_element_timeout.time = time;
                                        }
                                    }
                                    animation_timeout_3 = setTimeout(function() { // czas zycia obiektu
                                        if (index[3] !== 'none') {
                                            // jesli obiekt ma animation-constant to wylacz ta animacje w animacji wyjscia
                                            if (currObj.attr('animation-constant') !== 'none') {
                                                currObj.removeClass(currObj.attr('animation-constant'));
                                            }
                                            if (index[3] === 'off') {
                                                // schowaj
                                                currObj.hide();
                                            } else if (index[3].split('-')[0] === 'js') {
                                                // js
                                                currObj.hide(index[3].split('-')[1], { direction: index[3].split('-')[2] }, 1300);
                                            } else {
                                                // css3
                                                currObj.addClass(index[3]);
                                            }
                                        }

                                        if (last_element_timeout.actionkey === index[0]) {
                                            if (check_timeline_row(timeline_row)) {
                                                timeline_row++;
                                                handle_animations(timeline_transition[timeline_row], page);
                                            }
                                        }

                                        if (last_element_on_page(page) === index[0]){
                                            handle_end_page_actions();
                                        }
                                    }, time * 1000);
                                }
                                
                                
                            });
                        }
                    }, delaytime * 1000);
                break;
        }
    } else {
        return false;
    }
}

function add_over_animation(obj) {
    var animation = obj.attr('animation-over');
    
        
    if (typeof animation === 'string') {
        obj.mouseenter(function() {
            
            var that = $(this);
            
            if (!that.hasClass(animation)){
                that.addClass(animation);

                obj.bind('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd', function(e){
                        that.removeClass(animation);
                        obj.unbind('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd');
                }); 
            }
        });
    }

}

function add_constant_animation(obj) {
    var animation = obj.attr('animation-constant');
        
    if (typeof animation === 'string') {
            
            
            if (!obj.hasClass(animation)){
                obj.addClass(animation);

//                obj.bind('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd', function(e){
//                        mylog('TRANSITION ENDED!!!!!!.....');
//                        that.removeClass(animation);
//                        obj.unbind('animationend webkitAnimationEnd MSAnimationEnd oAnimationEnd');
//                }); 
            }
    }

}

function start_animation() {
    clear_visited_status(page);
    
    if(strony[page_order][2] == true) {
        lock_skin_navigation();
    }else if (strony[page_order][2] == false) {
        unlock_skin_navigation();
    }
    if(strony[page_order][4] == true) {
        lock_page_scrollbar();
    } else {
        unlock_page_scrollbar();
    }
    clearTimeout(animation_timeout_1);
    clearTimeout(animation_timeout_2);
    clearTimeout(animation_timeout_3);
    clearTimeout(animation_timeout_4);
    load_timeline_transition();
    timeline_row = 0;
    // sprawdzanie czy sa jakies punkty z animacjami na stronie
    if (timeline_tab[page-1][timeline_row] && timeline_tab[page-1][timeline_row][0]) {
    //if (timeline_tab[page_order][timeline_row] && timeline_tab[page_order][timeline_row][0]) {
        
        handle_animations(timeline_tab[page-1][timeline_row][0][4], page);
        sprawdz_status();
        sound_control();
        //handle_animations(timeline_tab[page_order][timeline_row][0][4], page_order+1);
    }
//    setTimeout(function() {
//        parallax_handler();
//    }, 50);
    
    
    //handle_animations(option);
    update_progress_bar();
}



function mute_page_handler(){
    
    var sm = window.frames[0].window.soundManager;
    
    var mainSound = $('#insideFrame').contents().find('#sound');
    var pointSound = $('#insideFrame').contents().find('#point-sound');
    var soundpresentation = $('#sound-presentation');
    
    // jesli strona nie jest wyciszona wycisz ją
    if (!mutepage) {
        
        // mute main sound for page
        if (mainSound.push() != 0)
            mainSound.get(0).volume = 0;
        
        if (pointSound.push() != 0)
            pointSound.get(0).volume = 0;
        
        if (soundpresentation.push() != 0)
            soundpresentation.get(0).volume =0;
        
        // mute all sounds on page
        sm.muteAll();
        
        // change main var 
        mutepage = true;
        
        
        // mute all swf objects on scene
        $('#insideFrame').contents().find('.div-point-swf').each(function(){
            $(this).flash(
                    function() {
                            this.SetVariable('/:swfsound', mutepage);
                    }
            );
        });
        
        $('#zoom').css('background-position', '-5px -95px');
    }
    
    // jeśli strona jest już wyciszona to uruchom dzwięki
    else {
        
        // unmute main sound for page
        if (mainSound.push() != 0)
            mainSound.get(0).volume = 1;
        
        if (pointSound.push() != 0)
            pointSound.get(0).volume = 1;
        
        if (soundpresentation.push() != 0)
            soundpresentation.get(0).volume = sound_vol / 100;
        
        // unmute all sounds on page
        sm.unmuteAll();
        
        // change main var 
        mutepage = false;
        
        // unmute all swf objects on scene
        $('#insideFrame').contents().find('.div-point-swf').each(function(){
            $(this).flash(
                    function() {
                            this.SetVariable('/:swfsound', mutepage);
                    }
            );
        });
        
        $('#zoom').css('background-position', '-5px -65px');
    }
    
}

function show_logo() {
    if ($('#logo').push() && logo_file != '') {
        var logo_w = $('#logo').width();
        var logo_h = $('#logo').height();
        
        if (logo_h < logo_size_h) {
            logo_size_w = parseInt((logo_h * logo_w) / logo_size_h);
            logo_size_h = logo_h;
        }
        
        var logo_top = 0;
        if (logo_size_h < logo_h) {
            logo_top = parseInt((logo_h - logo_size_h) / 2);
        }
        
        $('#logo').append('<img src="logo/' + logo_file + '" style="margin-top:' + logo_top + 'px;width:' + logo_size_w + 'px;height:' + logo_size_h + 'px;" />');
    } else {
        $('#logo').css('opacity', '0');
    }
}

// wlacz/wylacz tytuly
if (show_titles == 0)
    $('#pagename').hide();
    
show_logo();
//$('#logo').append('<img src="logo/' + logo_file + '" style="height:100%;" />');

// ======================================Doc ready function =====================================================

$(document).ready(function(){
    
    $('#screen').css('width', dimentions_x);
    $('#screen').css('height', dimentions_y);
    if( $('#pause').css('left') === '-745px') {
        $('#skin').css({
            'width': dimentions_x,
            'height': dimentions_y
        });
    }

    $('#screen').append('<div id="modal">\n\
        <div id="circularG">\n\
            <div id="circularG_1" class="circularG">\n\
            </div>\n\
            <div id="circularG_2" class="circularG">\n\
            </div>\n\
            <div id="circularG_3" class="circularG">\n\
            </div>\n\
            <div id="circularG_4" class="circularG">\n\
            </div>\n\
            <div id="circularG_5" class="circularG">\n\
            </div>\n\
            <div id="circularG_6" class="circularG">\n\
            </div>\n\
            <div id="circularG_7" class="circularG">\n\
            </div>\n\
            <div id="circularG_8" class="circularG">\n\
            </div>\n\
        </div>\n\
    </div>');
    $('#modal').show();
    $('#modal').css('height', dimentions_y + 'px');
    
    /*    pomoc obraz    */
    
    if (help_file != '') {
        $('#status-screen').text('').append('<img class="help-img" src="help/' + help_file + '" />');
        help_size_h = parseInt((help_size_h * 700) / help_size_w);
        help_size_w = 700;

        var status_screen_h = help_size_h;
        if ((help_size_h + 38) < 400)
            status_screen_h += 38;
            
	$( "#status-screen" ).dialog({
		title: help_title,
		autoOpen: false,
		resizable: false,
		draggable: false,
		modal: true,
		position: { my: "center", at: "center", of: skin },
		show: {
			effect: "fade",
			duration: 400
		},
		hide: {
			effect: "fade",
			duration: 400
		},
		width: 700,
		height: status_screen_h
	});
        
        $('.help-img').css('width', help_size_w + 'px').css('height', help_size_h + 'px');
    } else {
        $('#status').css('opacity', '0.5').css('cursor', 'pointer');
    }
    
    /*    end pomoc obrazek   */
    
    if (sound_presentation != '') {
        var soundl = '';
        if (sound_loop == 1)
            soundl = ' loop';
        
        $('body').append('<audio id="sound-presentation" src="sound/' + sound_presentation + '" autoplay' + soundl + '></audio>');
        $('#sound-presentation').get(0).volume = sound_vol / 100;
    }
    
    $('#insideFrame').css('opacity', '0');

	// ========== SCORM Functions =================

        var par = getURLParam();
        for (var paramName in par) {
            if (paramName == 'pageid') {
                page_id = par[paramName];
                
                $.each(strony, function(key, value) {
                    //mylog('key: ' + key + ', value: ' + value[1]);
                    if (strony[key][1] == parseInt(page_id)) {
                        page_order = parseInt(key);
                        page = strony[page_order][1];
                    }
                });
            }
                
        }
        
        
	initCourse();
        loadConfig();
        
        draw_elements();
        
        
        // zacznij prezentacje od danej strony
//        if (page_order != 0) {
            //$('#insideFrame').hide();
            //timeout = setTimeout(function(){
//                $('#zoom').removeClass('zoom-out').addClass('zoom-in');
                var view_true_dir;
                if (view_true == 'true')
                    view_true_dir = '_view';
                else
                    view_true_dir = '';
                if (my_attr == undefined || my_attr == '')
                    my_attr = '';
                
                $('#screen').append('<iframe id="insideFrame" style="background: none;visibility:hidden;" onload="this.style.visibility = \'visible\';" width="' + dimentions_x + '" height="' + dimentions_y + '" frameBorder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen ></iframe>');
                
                $("#insideFrame").css({
                    'display': 'none'
                });
                
                $("#insideFrame").attr("src", "exported" + view_true_dir + "/"+page+"/page.html" + my_attr).one("load", function() {
                    // pokaz insideFrame animacja
                    $(this).fadeIn(500);
                    $('#pagename').text(nazwa_strony[page-1]);
//                    sound_control();
//                    sprawdz_status();
//                    setLessonLocation(page_order);
                    currentPageStatus.start(page_order);
                });
                $("#counter").text((page_order+1)+'/'+all);
                
                // strony[page_order][0] = 1;
                
//                if(zaliczony()){
//                        setComplete();
//                }
            //}, 500);
//        } else {
//            $('#insideFrame').fadeIn(500);
//        }
        
		
	//popup
	$( "#toc-screen" ).dialog({
		title: 'Spis treści',
		autoOpen: false,
		resizable: false,
		draggable: false,
		modal: true,
		position: { my: "center", at: "center", of: skin },
		show: {
			effect: "fade",
			duration: 400
		},
		hide: {
			effect: "fade",
			duration: 400
		},
		width: 600,
		height: 340
	});

//	$( "#status-screen" ).dialog({
//		title: 'Activity status',
//		autoOpen: false,
//		resizable: false,
//		draggable: false,
//		modal: true,
//		position: { my: "center", at: "center", of: skin },
//		show: {
//			effect: "fade",
//			duration: 400
//		},
//		hide: {
//			effect: "fade",
//			duration: 400
//		},
//		width: 700,
//		height: 400
//	});
 
	$( "#toc" ).click(function() {
            $( "#toc-screen" ).dialog( "open" );
	});
    
	$( "#status" ).click(function() {
            if (help_file != '')
                $( "#status-screen" ).dialog( "open" );
	});
	

	
    // =====================================================
    
    // obsługa glownych przyciskow w opakowaniu =======================================================================
    var src_src = $("#insideFrame").attr('src');
    $("#insideFrame").attr("src", src_src).one("load", function() {
        //$(this).fadeIn(500);
        //sprawdz_status();
        mylog('cos tam dziala');
//        sound_control();
        //setLessonLocation(page_order);
    });
    
	
    

    $('#insideFrame').load(function() {
    //document.getElementById('insideFrame').contentWindow.onload = function() {
                //start_animation();
		loadFrameFunction();
//                sound_control();
//                if ($('#insideFrame').contents().find('#divimg').attr('zoom') == "url('../../imgpages/0')") {
//                    $('#zoom').css('opacity', '0.3');
//                }
            
                bindPrevBtn();
                bindNextBtn();
                
                if (page_order == 0){
                    unbindPrevBtn();
                } 
                else if (page_order > 0) {
                    bindPrevBtn();
                }
                if((page_order+1) < all) {
                    bindNextBtn();
                }
                else if((page_order+1) == all) {
                    unbindNextBtn();
                }


                $('#insideFrame').contents().find('#divimg div[actionkey]').each(function() {
                    if ($(this).attr('actionkey') == '15')
                        $(this).css('display', 'block');
                    else
                        $(this).css('display', 'none');
                    
                    if ($(this).attr('action') == '5')
                        $(this).css('border-color', $(this).attr('bordercolor'));
                    
                    if ($(this).attr('action') == '41' || $(this).attr('action') == '42' || $(this).attr('action') == '43')
                        $(this).css('border-color', $(this).attr('bordercolor'));
                });
                start_animation();
                $('#modal').fadeOut();
    });
    

//    $('#status').click(function() {
//        $('#status-end').text('');
//        
//
//        var i = 0;
//        var stat = '';
//        $.each(mypointstatus, function(key, value) {
//            $.each(mypointstatus[key], function(key2, value2) {
//                    if (value2[3] == '0')
//                        stat = '';
//                    else
//                        stat = '&#x2713';
//                    
//                    var action = value2[1];
//                    
//                    var actionString = '';
//                    switch(action)
//                    {
//                        case 1:
//                        case 11:
//                            actionString = lang['PUB_LINK'];
//                            break;
//                        case 2:
//                        case 3:
//                            actionString = lang['PUB_SOUND'];
//                            break;
//                        case 4:
//                            actionString = lang['PUB_GALLERY'];
//                            break;
//                        case 5:
//                            actionString = lang['PUB_SELECTION'];
//                            break;
//                        case 6:
//                            actionString = lang['PUB_POPUP'];
//                            break;
//                        case 9:
//                        case 10:
//                        case 16:
//                        case 31:
//                            actionString = lang['PUB_PICTURE'];
//                            break;
//                        case 15:
//                            actionString = lang['PUB_MASK'];
//                            break;
//                        case 12:
//                            actionString = lang['PUB_SWF'];
//                            break;
//                        case 99:
//                            actionString = lang['PUB_TEXT'];
//                            break;
//                        case 22:
//                            actionString = lang['PUB_QUIZ_MULTISELECT'];
//                            break;
//                        case 30:
//                            actionString = lang['PUB_QUIZ_RESULTS'];
//                            break;
//                        default:
//                            actionString = lang['PUB_DEFAULT'];
//                    }
//                    
//                    key = parseInt(key);
//                    key2 = parseInt(key2);
//                    
//                    $('#status-end').append('<div class="status-gotoscreen" id="status' + (key2+1) + '" type="button" strona="' + (key+1) + '">' + actionString + ', '+ lang['PUB_PAGE'] +' ' + (key+1) + '<span style="position:absolute;font-size:23px;right:20px;color:green;">' + stat + '</span></div>');
//                    //$('#status-end').append('<div class="status-gotoscreen" id="status' + (key2+1) + '" type="button" strona="' + (key+1) + '">' + actionString + ', '+ lang['PUB_PAGE'] +' ' + (key+1) + '<span style="position:absolute;font-size:23px;right:20px;color:green;">' + stat + '</span></div>');
//                    i++;
//             });
//        });
//    });
    
    $('#toc').click(function() {
        $('#toc-end').text('');
        for (var  i=0; i < Object.keys(nazwa_strony).length; i++ ) {
            if (strony[i][0] == 0)
                $('#toc-end').append('<div class="toc-gotoscreen" id="' + strony[i][1] + '" type="button">' + nazwa_strony[strony[i][1] - 1] + '</div>');
            else
                $('#toc-end').append('<div class="toc-gotoscreen" id="' + strony[i][1] + '" type="button">' + nazwa_strony[strony[i][1] - 1] + '<span style="position:absolute;font-size:23px;color:green;right: 20px;font-family:\'Comic Sans MS\'">&#x2713;</span></div>');
        }
    });
     
    // funkcja zoom
    $('#zoom').click(function() {
        //alert('zoom nie dziala');
        
        mute_page_handler();

//        var $image = $('#insideFrame').contents().find('#divimg');
//        
//        if ($image.attr('zoom') != "url('../../imgpages/0')") {
//            if(!($image.hasClass('zoomed'))){
//                
//                $image.css('width', (parseInt($image.css('width')))*2+'px');
//                $image.addClass('zoomed');
//                atrybut1 = $image.css('background-image');
//                atrybut2 = $image.attr('zoom');
//                atrybut3 = $image.css('height');
//                atrybut4 = $image.attr('zoomh');
//                atrybut5 = $image.attr('top')
//                //atrybut6
//                $image.css('background-image', atrybut2).attr('zoom', atrybut1).css('height', atrybut4).attr('zoomh', atrybut3).css('background-position','0px -' + (atrybut5*2) + 'px');
//
//                $('#insideFrame').contents().find('.point, .divsound').each(function() {
//                    var x = parseInt($(this).css('left'));
//                    var y = parseInt($(this).css('top'));
//                    var width = parseInt($(this).css('width'));
//                    var height = parseInt($(this).css('height'));
//
//                    $(this).css('left', (x * 2) + 'px');
//                    $(this).css('top', (y * 2) + 'px');
//
//                    if ($(this).hasClass('pointr')) {
//                        $(this).css('left', (x * 2 + (width / 2)) + 'px');
//                        $(this).css('top', (y * 2 + (height / 2)) + 'px');
//                    }
//                    // powiekszanie zaznaczonego obszaru
//                    if ($(this).hasClass('select')) {
//
//                        $(this).css('width', (width * 2) + 'px');
//                        $(this).css('height', (height * 2) + 'px');
//                    }
//                });
//                $('#insideFrame').contents().scrollLeft(400);
//                $('#insideFrame').contents().find('body').css('overflow-x', 'visible');
//                //$('#insideFrame').contents().scrollLeft(400);
//                //$('#zoom').css('background-image', 'url("skin/buttons/zoom_out.png")');
//                $('#zoom').removeClass('zoom-in').addClass('zoom-out');
//            } else {
//                $image.css('width', (parseInt($image.css('width')))/2+'px');
//                $image.removeClass('zoomed');
//                atrybut1 = $image.css('background-image');
//                atrybut2 = $image.attr('zoom');
//                atrybut3 = $image.css('height');
//                atrybut4 = $image.attr('zoomh');
//                atrybut5 = $image.attr('top');
//                $image.css('background-image', atrybut2).attr('zoom', atrybut1).css('height', atrybut4).attr('zoomh', atrybut3).css('background-position', '0px -' + atrybut5 + 'px');
//                $('#insideFrame').contents().find('.point, .divsound').each(function() {
//                    var x = parseInt($(this).css('left'));
//                    var y = parseInt($(this).css('top'));
//                    var width = parseInt($(this).css('width'));
//                    var height = parseInt($(this).css('height'));
//
//                    $(this).css('left', (x / 2) + 'px');
//                    $(this).css('top', (y / 2) + 'px');
//
//                    if ($(this).hasClass('pointr')) {
//                        $(this).css('left', ((x - (width / 2)) / 2));
//                        $(this).css('top', ((y - (height / 2)) / 2));
//                    }
//                    // zmniejszanie zaznaczonego obszaru
//                    if ($(this).hasClass('select')) {
//                        $(this).css('width', (width / 2) + 'px');
//                        $(this).css('height', (height / 2) + 'px');
//                    }
//                });
//                $('#insideFrame').contents().find('body').css('overflow-x', 'hidden');
//                //$('#zoom').css('background-image', 'url("skin/buttons/zoom_in.png")');
//                $('#zoom').removeClass('zoom-out').addClass('zoom-in');
//            }
//        }
    });
    
    $('#play').click(function() {
        var sound = $('#insideFrame').contents().find('#sound');
        if (sound.push() != 0)
            sound.get(0).play();
    });
    
    $('#pause').click(function() {
        var sound = $('#insideFrame').contents().find('#sound');
        if (sound.push() != 0)
            sound.get(0).pause();
    });
    
    $('#stop').click(function() {
        var sound = $('#insideFrame').contents().find('#sound');
        if (sound.push() != 0) {
            sound.get(0).pause();
            sound.get(0).currentTime=0;
        }
    });
    
    setTimeout(function() {
        //sound_control();
    }, 200);


    nextScreenFn = function() {
        if ((page_order+1) != all){
            $('#modal').fadeIn('fast');
            $('#insideFrame').fadeOut(500);
            timeout = setTimeout(function(){
                    
                var view_true_dir;
                if (view_true == 'true')
                    view_true_dir = '_view';
                else
                    view_true_dir = '';
                if (my_attr == undefined || my_attr == '')
                    my_attr = '';
                
                $("#insideFrame").attr("src", "exported" + view_true_dir + "/"+page+"/page.html" + my_attr).one("load", function() {
                    $(this).fadeIn(500);
                    $('#pagename').text(nazwa_strony[page-1]);
                    setLessonLocation(page_order);
                    currentPageStatus.start(page_order);
                });
                $("#counter").text((page_order+1)+'/'+all);

            }, 500, page_order++, page = strony[page_order][1]);
        }
    }
    
//    bindNextBtn();
    
    prevScreenFn = function(){
        if ((page_order+1) != 1){
            $('#modal').fadeIn('fast');
            $('#insideFrame').fadeOut(500);
            timeout = setTimeout(function(){
                    
                //page--;
                //if (page < 1) page = 1;
                //$('#zoom').removeClass('zoom-out').addClass('zoom-in');
                var view_true_dir;
                if (view_true == 'true')
                    view_true_dir = '_view';
                else
                    view_true_dir = '';
                
                if (my_attr == undefined || my_attr == '')
                    my_attr = '';
                
                $("#insideFrame").attr("src", "exported" + view_true_dir + "/"+page+"/page.html" + my_attr).one("load", function() {
                    $(this).fadeIn(500);
                    $('#pagename').text(nazwa_strony[page-1]);
//                    sprawdz_status();
//                    sound_control();
                    setLessonLocation(page_order);
                    currentPageStatus.start(page_order);
                });
                $("#counter").text((page_order+1)+'/'+all);
                /*$('#insideFrame').fadeIn(500, function() {
                    sprawdz_status();
                    sound_control();
                });*/
                // strony[page_order][0] = 1;
//                if(zaliczony()){
//                    setComplete();
//                }
                //start_animation();
            }, 500, page_order--, page = strony[page_order][1]);
        } 
    }
    
    $('#previous').css('opacity', '.2');
        
//     bindPrevBtn();
    
	// przyciski TOC
	
        
	$(document).on('click', '.toc-gotoscreen', (function(){
            $('#modal').fadeIn('fast');
            page = $(this).attr('id');
            //page_order = (parseInt($(this).attr('id')) - 1);
            //page = strony[page_order][1];
            //strony[pageorder][1] = paga
            
            $.each(strony, function(key, value) {
                if (strony[key][1] == parseInt(page)) {
                    page_order = parseInt(key);
                    //page = strony[page_order][1];
                }
            });

            $('#insideFrame').fadeOut(500);
            timeout = setTimeout(function(){
                //$('#zoom').removeClass('zoom-out').addClass('zoom-in');
                var view_true_dir;
                if (view_true == 'true')
                    view_true_dir = '_view';
                else
                    view_true_dir = '';
                if (my_attr == undefined || my_attr == '')
                    my_attr = '';
                
                $("#insideFrame").attr("src", "exported" + view_true_dir + "/"+page+"/page.html" + my_attr).one("load", function() {
                    $(this).fadeIn(500);
                    $('#pagename').text(nazwa_strony[page-1]);
//                    sprawdz_status();
//                    sound_control();
                    setLessonLocation(page_order);
                    currentPageStatus.start(page_order);
                });
                $("#counter").text((page_order+1)+'/'+all);
                /*$('#insideFrame').fadeIn(700, function() {
                    sprawdz_status();
                    sound_control();
                });*/
                // strony[page_order][0] = 1;
                
//                if(zaliczony()){
//                        setComplete();
//                }
                
            }, 800);
            //start_animation();
            $('#toc-screen').dialog("close");
	}));
	
        // przyciski status
//	$(document).on('click', '.status-gotoscreen', (function(){
//            $('#modal').fadeIn('fast');
//            page = $(this).attr('strona');
//            $.each(strony, function(key, value) {
//                if (strony[key][1] == parseInt(page)) {
//                    page_order = parseInt(key);
//                    //page = strony[page_order][1];
//                }
//            });
//
//            $('#insideFrame').fadeOut(700);
//            timeout = setTimeout(function(){
//                //$('#zoom').removeClass('zoom-out').addClass('zoom-in');
//                var view_true_dir;
//                if (view_true == 'true')
//                    view_true_dir = '_view';
//                else
//                    view_true_dir = '';
//                if (my_attr == undefined || my_attr == '')
//                    my_attr = '';
//                
//                //$("#insideFrame").attr("src", "exported" + view_true_dir + "/"+page+"/page.html" + my_attr).one("load", function() {
//                $("#insideFrame").attr("src", "exported" + view_true_dir + "/"+page+"/page.html" + my_attr).one("load", function() {
//                    $(this).fadeIn(500);
//                    $('#pagename').text(nazwa_strony[page-1]);
//                    sprawdz_status();
//                    sound_control();
//                    setLessonLocation(page_order);
//                });
//                $("#counter").text((page_order+1)+'/'+all);
//                /*$('#insideFrame').fadeIn(700, function() {
//                    sprawdz_status();
//                });*/
//                strony[page_order][0] = 1;
//                
//                if(zaliczony()){
//                        setComplete();
//                }
//            }, 800);
//            //start_animation();
//            $('#status-screen').dialog("close");
//	}));

    window.onbeforeunload = function(){
        saveDScorm();
    };

});

// ===================================== END OF DOC REDY ===========================================================


function update_progress_bar() {
    var progressbar = $('#progressbar');

    if (!progressbar.push())
        return;

    if (progressbar.push() === 1 && progressbar.css('display') !== "none") {
        var perc = ((page_order+1) / all) * 100;
        progressbar.find('#progressbar-inside').css('width', perc + "%");
    }
}

function mylog(msg) {
    if (debugmode == true) 
        console.log(msg);
}