var totalPages = 0;
var canvas, stage, exportRoot;
var epOrgW = 0;
var feedbackTimeout;
var mainPage, exercisePage;
var lastCheckOrient;
var startImageLoaded = false;
var soundExt = '.mp3';
/* -----------------------------------------------------------------------------*/
/* Prepare Function */
/* -----------------------------------------------------------------------------*/
function preparePages() {
    $('body').append('\
	<div id="pt-main" class="pt-perspective"></div>\
	<div class="pt-message">\
		<p>Twoja przeglądarka nie obsługuje prawidłowo zasobów HTML5.</p>\
	</div>\
	<div id="modal" class="modal fade">\
            <div class="modal-dialog">\
                    <div class="modal-content">\
                        <div class="modal-header">\
                            <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>\
                            <h4 class="modal-title">Instrukcja</h4>\
                        </div>\
                        <div class="modal-body">\
                        </div>\
                        <div class="modal-footer">\
                            <button type="button" class="btn btn-warning" data-dismiss="modal">Zamknij</button>\
                            <!--button type="button" class="btn btn-primary">Zapisz</button-->\
                        </div>\
                    </div>\
            </div>\
	</div>\
        <div class="pt-loader">\
            <div>\
		<p><img src="' + fwDir + '/mono-interactive/images/loader.gif"/></p>\
		<!--p class="exercise-start">Trwa ładowanie ...</p-->\
            </div>\
	</div>');
    mainPage = insertPage();
    $(mainPage).append('\
	<div class="exercise">\
            <div class="exercise-title"><div class="bg-left"><div class="bg-right"><div class="bg-fill"><div class="text"></div></div></div></div></div>\
            <div class="exercise-footer">\
                <div class="exercise-start" onclick="loadExercisePage();"><div class="text">Uruchom</div></div>\
                <div class="exercise-logos">\
                    <div class="left col-xs-6"><img src="' + fwDir + '/mono-interactive/images/logo-kpl.png" class="kl-logo img-responsive"></div>\
                    <div class="right col-xs-6"><img src="' + fwDir + '/mono-interactive/images/logo-ue.png" class="ue-logo img-responsive"></div>\
                    <div class="ue-text col-xs-12">Projekt współfinansowany przez Unię Europejską w ramach Europejskiego Funduszu Społecznego.</div>\
                </div>\
            </div>\
	</div>\
    ');

    exercisePage = insertPage();
    $(exercisePage).append('\
	<div class="exercise">\
            <div class="exercise-header">\
                <div class="exercise-panel">\
                    <div class="exercise-text"><div class="btn-icon icon-info" onclick="exercisePanel();"><div class="text"></div></div></div>\
                </div>\
            </div>\
            <div class="exercise-content"><canvas width="' + lib.properties.width + '" height="' + lib.properties.height + '" style="background-color:rgba(255,0,0,0);"></canvas></div>\
            <div class="exercise-nav">\
                <div class="btn-icon icon-menu" onclick="exercisePanel();"></div>\
                <div class="btn-icon icon-restart" onclick="exerciseRestart();"></div>\
                <div class="btn-icon icon-faq" onclick="exerciseFaq();"></div>\
                <div class="btn-icon icon-contrast" onclick="exerciseContrast();"></div>\
            </div>\
	</div>');

    endPage = insertPage();
    $(endPage).append('\
	<div class="exercise">\
            <div class="exercise-title"><div class="bg-left"><div class="bg-right"><div class="bg-fill text">\
            Gratulacje!<br/>\
            <small>Teraz zamknij to okno i przejdź do kolejnego zasobu, ćwiczenia lub gry.</small>\
            </div></div></div></div>\
            <div class="exercise-footer">\
                <div class="exercise-logos">\
                    <div class="left col-xs-6"><img src="' + fwDir + '/mono-interactive/images/logo-kpl.png" class="kl-logo img-responsive"></div>\
                    <div class="right col-xs-6"><img src="' + fwDir + '/mono-interactive/images/logo-ue.png" class="ue-logo img-responsive"></div>\
                    <div class="ue-text col-xs-12">Projekt współfinansowany przez Unię Europejską w ramach Europejskiego Funduszu Społecznego.</div>\
                </div>\
            </div>\
	</div>\
    ');

    /* Loading images */
    canvas = $('canvas', exercisePage)[0];

    for (res in lib.properties.manifest) {
        lib.properties.manifest[res]['src'] = assetsDir + '/' + lib.properties.manifest[res]['src'];
    }

    images = images || {};

    var loader = new createjs.LoadQueue(false);
    loader.addEventListener("fileload", handleFileLoad);
    loader.addEventListener("complete", handleComplete);
    loader.loadManifest(lib.properties.manifest);

    var pid = parseInt(getResourceProjectId(getResourceId()));
    /* Loading default  sounds */
    soundExt = checkAudioCompitable();
    createjs.Sound.addEventListener("fileload", handleFileLoad);
    
    if(soundExt === '.mp3')
        createjs.Sound.alternateExtensions = ["ogg"];
    else
        createjs.Sound.alternateExtensions = ["mp3"];

    switch (pid) {
        case 1:
            createjs.Sound.registerManifest([
                {id: "ssBadAnswer", src: "ssBadAnswer" + soundExt},
                {id: "ssGoodAnswer", src: "ssGoodAnswer" + soundExt},
                {id: "ssBrawa", src: "ssBrawa" + soundExt},
                {id: "ssDice", src: "ssDice" + soundExt},
                {id: "ssFanfary", src: "ssFanfary" + soundExt},
                {id: "ssMagicBall", src: "ssMagicBall" + soundExt},
                {id: "ssPawn", src: "ssPawn" + soundExt}
            ], getFrameworkAssetDir() + '/sounds/01/');
            break;
        case 2:
            createjs.Sound.registerManifest([
                {id: "ssBadAnswer", src: "ssBadAnswer" + soundExt},
                {id: "ssGoodAnswer", src: "ssGoodAnswer" + soundExt},
                {id: "ssBrawa", src: "ssBrawa" + soundExt},
                {id: "ssBrush", src: "ssBrush" + soundExt},
                {id: "ssDice", src: "ssDice" + soundExt},
                {id: "ssFanfary", src: "ssFanfary" + soundExt},
                {id: "ssGratuluje", src: "ssGratuluje" + soundExt},
				{id: "ssMagicBall", src: "ssMagicBall" + soundExt},
                {id: "ssPawn", src: "ssPawn" + soundExt},
                {id: "ssThanks", src: "ssThanks" + soundExt}
            ], getFrameworkAssetDir() + '/sounds/02/');
            break;
        case 3:
            createjs.Sound.registerManifest([
                {id: "ssBadAnswer", src: "ssBadAnswer" + soundExt},
                {id: "ssGoodAnswer", src: "ssGoodAnswer" + soundExt},
                {id: "ssBrawa", src: "ssBrawa" + soundExt},
                {id: "ssBrawo", src: "ssBrawo" + soundExt},
                {id: "ssBrush", src: "ssBrush" + soundExt},
                {id: "ssDice", src: "ssDice" + soundExt},
                {id: "ssFanfary", src: "ssFanfary" + soundExt},
				{id: "ssMagicBall", src: "ssMagicBall" + soundExt},
                {id: "ssPawn", src: "ssPawn" + soundExt}
            ], getFrameworkAssetDir() + '/sounds/03/');
            break;
    }

	if (typeof feedbackAnimation === 'object') {
		var animParams = feedbackAnimation.internedStrings;
		var animSounds = [];
		animSounds = searchSounds(feedbackAnimation, 'html5sound_', animSounds);

		if (animSounds.length > 0) {
			for (var i = 0; i < animSounds.length; i++) {
				createjs.Sound.registerSound({id: animSounds[i], src: getAssetDir() + '/sounds/' + animSounds[i] + soundExt});
			}
		}
	}
}

/* -----------------------------------------------------------------------------*/
/* Exercise Functions */
/* -----------------------------------------------------------------------------*/

function exerciseContrast() {
    $('body').toggleClass('contrast');
    //alert('Przełączenie na tryb wysokiego kontrastu jest niedostpne w tej konfiguracji.');
}

function exerciseFaq() {
    showMessage(getOrderInfo(), 'Instrukcja');
}

function exercisePanel() {
    $('.exercise-header').toggleClass('short');
    $('.exercise-nav').toggleClass('short');
}

function exercisePanelHide() {
    $('.exercise-header').addClass('short');
    $('.exercise-nav').addClass('short');
}

function exerciseRestart() {
    window.location.href = window.location.href;
}

function exerciseReady() {
    var pid = parseInt(getResourceProjectId(getResourceId()));
    $('body').addClass('body-' + pid)

    var title = getResourceTitle(getResourceId());
    window.document.title = top.document.title = title;

    $('.pt-page-1 .exercise-title .text').text(title);
    $('.pt-page-2 .exercise-text .text').text(config.title);

    switch (pid) {
        case 1:
            $('.pt-page-3 .exercise-title .text').html('Super!<br/><small>Teraz zamknij to okno i przejdź do kolejnego zasobu, ćwiczenia lub gry.</small>');
            break;
        case 2:
            $('.pt-page-3 .exercise-title .text').html('Brawo!<br/><small>Jeżeli chesz przejść do kolejnego zasobu, ćwiczenia lub gry zamknij to okno.</small>');
            break;
        case 3:
            $('.pt-page-3 .exercise-title .text').html('Gratulacje!<br/><small>Teraz możesz zamknąć to okno i przejść do kolejnego zasobu, ćwiczenia lub gry.</small>');
            break;
    }

    if (config.type === 'animation') {
        $('.pt-page-3 .exercise-title .text').html('Dziękujemy!<br/><small>Teraz zamknij to okno i przejdź do kolejnego zasobu, ćwiczenia lub gry.</small>');
    }

    $('.exercise-content').on('mousedown touchstart', function() {
        exercisePanelHide();
    });
}

/* -----------------------------------------------------------------------------*/
/* Handling Functions */
/* -----------------------------------------------------------------------------*/

function handleFileLoad(evt) {
    if (evt)
        if (evt.item)
            if (evt.item.type === "image") {
                images[evt.item.id] = evt.result;
            }
}

function handleComplete() {
    exportRoot = new lib.index();
    stage = new createjs.Stage(canvas);
    createjs.Touch.enable(stage);

    stage.enableMouseOver(10);
    stage.mouseMoveOutside = true;
    stage.addChild(exportRoot);
    stage.update();

    createjs.Ticker.setFPS(lib.properties.fps);
    createjs.Ticker.addEventListener("tick", stage);
    $(window).resize(function() {
        onResize();
    });

    onResize();
    hideLoader();
    initExercise();
    checkBrowser();
}

function hideLoader() {
    $('.pt-loader').animate({opacity: 0}, 300, function() {
        $('.pt-loader').hide();
    });
}

/* -----------------------------------------------------------------------------*/
/* Init Functions */
/* -----------------------------------------------------------------------------*/

function initExercise() {
    initPageTransitions();
    exerciseOnStart();
}

function insertPage() {
    totalPages++;
    $('#pt-main').append('<div id="page' + totalPages + '" class="pt-page pt-page-' + totalPages + '">\</div>');
    var pageId = $('#page' + totalPages);
    return pageId;
}

function loadExercisePage() {
    playSound('ssPawn');
    if (config.type === 'animation') {
        $('.pt-page-2 .exercise').html('');
        PageTransitions.nextPage(28, function() {
            loadFeedbackAnimationComplete();
        }, 1000);
    }
    else {
        PageTransitions.nextPage(28, function() {
            showExercise();
        });
    }
}

function loadFeedbackAnimation() {
    TweenMax.to($('.pt-page-2 .exercise'), 1, {
        alpha: 0,
        onComplete: loadFeedbackAnimationComplete
    });
}

function loadFeedbackAnimationComplete() {
    $('.pt-page .exercise').show();
    $('.pt-page-2 .exercise').html('');
    $('.pt-page-2 .exercise').parent().prepend('<div id="fbAnim" style="width:900px;height:600px;"></div>');
    TweenMax.to($('#fbAnim'), 0, {
        alpha: 0
    });
    if (typeof feedbackAnimation === 'object') {
        onResize = onResizeFb;
        onResize();
        fbAnim = new swiffy.Stage(document.getElementById('fbAnim'), feedbackAnimation, {});
        fbAnim.start();
        fbAnim.setBackground(null);
        TweenMax.to($('#fbAnim'), 1, {
            alpha: 1
        });
    }

    if (config.type === 'animation') {
        feedbackTimeout = setTimeout(function() {
            closeFeedback();
        }, 50000);
    }
    else {
        feedbackTimeout = setTimeout(function() {
            closeFeedback();
        }, 20000);
    }
}

/* -----------------------------------------------------------------------------*/
/* Extra Functions */
/* -----------------------------------------------------------------------------*/

function checkAudioCompitable() {
    if (typeof Modernizr !== 'undefined') {
        if (Modernizr.audio.ogg !== '') {
            return '.ogg';
        }
        if (Modernizr.audio.mp3 !== '') {
            return '.mp3';
        }
    }
    else {
        return '.mp3';
    }
}

function checkBrowser() {
    var compitableBrowser = false;
    var webkit = checkBrowserWebKit();
    var browser = [checkBrowserName(), checkBrowserVersion()];

    if (webkit !== null) {
        webkit = webkit.toString().split('.');
        if (webkit[0] > '536' && parseInt(webkit[1]) > 22)
            compitableBrowser = true;
    }

    if (browser[0] === 'Chrome')
        if (browser[1] > 36)
            compitableBrowser = true;

    if (browser[0] === 'Firefox')
        if (browser[1] > 34)
            compitableBrowser = true;

    if (browser[0] === 'IE')
        if (browser[1] > 10)
            compitableBrowser = true;

    if ($('html').hasClass('canvas') &&
        $('html').hasClass('svg') &&
        $('html').hasClass('video') &&
        $('html').hasClass('audio') &&
        $('html').hasClass('csstransforms')
    )
    compitableBrowser = true;

    if (compitableBrowser !== true) {
        checkCookie('showalert', 'true', function() {
            var title = 'Twoja przeglądarka nie obsługuje poprawnie HTML5';
            var message = 'Drogi użytkowniku,<br/></br>Zalecamy korzystanie z <b>aktualnych wersji przeglądarek</b>, co pozwoli bezproblemowo korzystać z niniejszego zasobu.</br></br>Aby uzyskać jak największą wydajność wysokiej jakości zasobów HTML5  <b>zalecamy instalację</b> nowoczesnej przeglądarki <b>Google Chrome</b> w najnowszej wersji lub aktualizację obecnej przeglądarki do najnowszej wersji.'
            showMessage(message, title);
        });
    }
}

function checkBrowserWebKit() {
    var result = /AppleWebKit\/([\d.]+)/.exec(navigator.userAgent);
    if (result) {
        return parseFloat(result[1]);
    }
    return null;
}

function checkBrowserName() {
    var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if (/trident/i.test(M[1])) {
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE';
    }
    if (M[1] === 'Chrome') {
        tem = ua.match(/\bOPR\/(\d+)/)
        if (tem != null) {
            return 'Opera';
        }
    }
    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if ((tem = ua.match(/version\/(\d+)/i)) != null) {
        M.splice(1, 1, tem[1]);
    }
    return M[0];
}

function checkBrowserVersion() {
    var ua = navigator.userAgent, tem, M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if (/trident/i.test(M[1])) {
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        return tem[1];
    }
    if (M[1] === 'Chrome') {
        tem = ua.match(/\bOPR\/(\d+)/)
        if (tem != null) {
            return tem[1];
        }
    }
    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if ((tem = ua.match(/version\/(\d+)/i)) != null) {
        M.splice(1, 1, tem[1]);
    }
    return M[1];
}

function checkOrient() {
    var currentOrient = 'h';
    if ($(window).height() > $(window).width())
        currentOrient = 'v';

    if (lastCheckOrient != currentOrient) {
        lastCheckOrient = currentOrient;
        if (currentOrient === 'v') {
            if (mobilecheck())
                showMessage('Prosimy o zmianę orientacji ekranu z pionowej na poziomą.', 'Zmień orientację ekranu!');
            else
                showMessage('Prosimy o poszerzenie okna aplikacji.', 'Zmień rozmiar okna!');
        } else {
            $('#modal').modal('hide');
        }
    }
}

function closeFeedback() {
    clearTimeout(feedbackTimeout);

    setTimeout(function() {
        PageTransitions.nextPage(28, function() {
        });
    }, 3000);

    closeFeedback = function() {
    }
}

/* -----------------------------------------------------------------------------*/
/* Resize Functions */
/* -----------------------------------------------------------------------------*/

function onResize() {
    var panelH = $('.exercise-header').height();
    var panelW = $('.exercise-header').width();
    var panelBottomH = $('.exercise-nav').height();
    var panelBottomW = $('.exercise-nav').width();
    var innerW = $('#pt-main').width();
    var innerH = $('#pt-main').height();
    var innerSpace = 60;

    var canvasW = lib.properties.width;
    var canvasH = lib.properties.height;
    //var canvasS = Math.min((innerW / canvasW), ((innerH - panelH - panelBottomH) / canvasH));
    var canvasS = Math.min(((innerW - innerSpace) / canvasW), ((innerH - innerSpace) / canvasH));

    var containerW = canvasW * canvasS;
    var containerH = canvasH * canvasS;

    var containerL = (innerW - containerW) / 2;
    var containerT = (innerH - containerH) / 2;

    $('.pt-page .exercise-content').each(function() {
        $(this).css({
            'transform': 'scale(' + canvasS + ')',
            '-webkit-transform': 'scale(' + canvasS + ')',
            'transform-origin': 'left top',
            '-webkit-transform-origin': 'left top'
        });

        var eP = $(this).parent().parent().find('.exercise-header');
        if (epOrgW === 0)
            epOrgW = $(eP).width();
        var epW = epOrgW;
        if (innerW < epW)
            epW = innerW;

        $(this).parent().parent().find('.exercise-content').css({
            'width:': containerW + 'px',
            'height:': containerH + 'px',
            'margin-left': containerL + 'px',
            'margin-top': containerT + 'px'
        });
    });

    if (typeof config.align !== 'undefined') {
        if (config.align === 'top')
            $('.exercise-content').css('margin-top', '0px');
    }

    var top = ($(window).height() - $('.pt-page-1 .exercise-footer').height() - $('.pt-page-1 .exercise-title').height()) / 2;
    if (top <= 30)
        top = 30;

    if (!startImageLoaded)
        $('.pt-page-1 .exercise-title').css('top', top + 'px');

    checkOrient();
}

function onResizeFb() {
    var innerW = $('#pt-main').width();
    var innerH = $('#pt-main').height();

    var canvasW = $('#fbAnim').width();
    var canvasH = $('#fbAnim').height();

    var canvasS = Math.min((innerW / canvasW), (innerH / canvasH));

    var canvasL = (innerW - canvasW) / 2;
    var canvasT = (innerH - canvasH) / 2;

    $('#fbAnim').css({
        'width': innerW,
        'height': innerH
    });

    var top = ($(window).height() - $('.pt-page-3 .exercise-footer').height() - $('.pt-page-3 .exercise-title').height()) / 2;
    if (top <= 30)
        top = 30;
    $('.pt-page-3 .exercise-title').css('top', top + 'px');

    checkOrient();
}

function searchSounds(obj, pattern, results) {
    for (var i in obj) {
        if (obj[i] !== null && typeof obj[i] !== 'undefined') {
            if (typeof obj[i] === "object") {
                searchSounds(obj[i], pattern, results);
            }
            else {
                if (obj[i].toString().indexOf(pattern) > -1) {
                    //results.push({id: obj[i], src: obj[i] + '.mp3'});
                    results.push(obj[i]);
                }
            }
        }
    }
    return results;
}

/* -----------------------------------------------------------------------------*/
/* Cookie Functions */
/* -----------------------------------------------------------------------------*/
function checkCookie(name, value, callback) {
    //delCookie(name);
    var cookie = getCookie(name);
    //console.log(name, value, cookie);
    if (cookie !== '') {
        if (cookie !== value) {
            callback();
        }
    } else {
        if (typeof value !== 'undefined') {
            callback();
            setCookie(name, value, 4);
        }
    }
}

function delCookie(name) {
    //console.log('Delete Cookie: ' + name);
    document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}

function getCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) != -1)
            return c.substring(name.length, c.length);
    }
    return "";
}

function setCookie(cname, cvalue, exhours) {
    //console.log('Set Cookie: ' + name);
    var d = new Date();
    d.setTime(d.getTime() + (exhours * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

