﻿var imagesPreloader = {
    imagesHTML: null,

    counter: 0,
    imagesNr: 0,
    finished: false,

    progressWidth: 392,

    progressNode: null,
    oneProgressPercent: null,

    onFinish: null,

    init: function(onFinishFunctionPointer) {
        this.oneProgressPercent = this.progressWidth / this.imagesNr;
        this.progressNode = document.getElementById('imagesPreloaderProgressNode');

        var imagesPreloaderStatus = document.getElementById('preloaderStatusTextBox').value;
        if (imagesPreloaderStatus == 'done') {
            /*this.counter = this.imagesNr;
            this.updateProgressPanel();
            this.finished = true;

            if (this.onFinish != null) {
                this.onFinish();
            }*/
        }
        else {
            document.getElementById('imagesPreloader').innerHTML = this.imagesHTML;
            this.onFinish = onFinishFunctionPointer;
        }
    },

    addCounter: function() {
        this.counter++;
        if (this.counter > this.imagesNr) {
            this.counter = this.imagesNr;
        }

        this.updateProgressPanel();

        if (this.counter == this.imagesNr) {
            this.finished = true;

            if (this.onFinish != null) {
                this.onFinish();
            }
        }
    },

    updateProgressPanel: function() {
        this.progressNode.style.width = this.counter * this.oneProgressPercent + 'px';

        var progressPercent = Math.round(this.counter * 100 / this.imagesNr);
        document.getElementById('imagesLoadingProgressSpan').innerHTML = progressPercent;

        if (progressPercent > 90) {
            setTimeout('imagesPreloader.emergencyImgLoadCheck()', 5000);
        }
    },

    emergencyImgLoadCheck: function() {
        if (this.counter < this.imagesNr) {
            this.addCounter();
        }
    },

    checkPreloaderCookie: function() {
        var cookieValue = helper.readCookie('lastImagesPreload');
        if (cookieValue) {
            var now = new Date();
            var day = now.getDate()
            var month = now.getMonth() + 1;
            var year = now.getYear();

            var dateString = day + '.' + month + '.' + year;
            if (dateString == cookieValue) {
                return true;
            }
            else {
                return false;
            }
        }
        else {
            return false;
        }
    },

    setPreloaderCookie: function() {
        var now = new Date();
        var day = now.getDate()
        var month = now.getMonth() + 1;
        var year = now.getYear();

        var dateString = day + '.' + month + '.' + year;
        helper.createCookie('lastImagesPreload', dateString, 7);
    }
}
