// slide script
// used from:
// http://sixrevisions.com/tutorials/javascript_tutorial/create-a-slick-and-accessible-slideshow-using-jquery/
// updated OO approuch should be reviewed: http://bicorner.wordpress.com/2010/01/24/slideshow-using-javascript-and-jquery-1-4/#more-11
// anothe looking good oo approuch:http://www.offcode.it/javascript/slideshow/#
// fonts styling in em's: http://v1.jontangerine.com/log/2007/09/the-incredible-em-and-elastic-layouts-with-css

/*
 controls and slides
 z-index'es
 9 - menulist
 
 */
var printMode = 0;
var testsList = [];
var testScrollBar;
var marginTop = 0;
var downCounter = 0;

function printRezults(){
        
        var isInIframe = (window.location != window.parent.location) ? true : false;
        
        if (isInIframe){
            window.parent.$('iframe').get(0).contentWindow.print();
        }else{
           window.print();
        }       
}

// if it is true, then test buttone is not shown and report is generated.

function test_finish_report() {
    console.log('JSF test_finish_report()');
    sectionName = 'section' + inSection;
    var section = doContent[sectionName];
    var $section = $('#section' + inSection);

    var i = 0;
    var right_answers = 0;

    prepend_test_section($section);
    $('.slide').css({'height': '718px'});

    for (slide in section) {
        prepare_slide_report(slide);
        i++;
    }

    append_test_report_details(i, right_answers);
    answer_css();
    remove_unnecessary();

    function prepend_test_section($section) {
        $section
                .css({
            'margin': '0',
            'margin-top': '0',
            'padding': '0px',
            'height': 'auto'
        })
                .prependTo('body');
    }
    function prepare_slide_report(slide) {
        console.log('Answer line:' + slide);
        slideName = slide;
        ss = sectionName + slideName; // section and slide name
        ssId = '#' + ss; // section and slide name

        // check if slide is iniciated, if not, create slide
        var answer_icon;
        var answer_background;
        var answer_border;
        var scriptObj = doContent[sectionName][slide]['script'];

        if (scriptObj['iniciated']) {
            var answer = test_answer_check(slide);
            if (answer) {
                right_answer();
            }
            else {
                wrong_answer();
            }
        }
        else {
            not_answered();
        }

        function test_answer_check(slide) {
            var answer = '';
            if (typeof section[slide].get_answer_result != 'undefined') {
                var answer_check = section[slide].get_answer_result();
                answer = section[slide].answer_result;
                console.log('Test result >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>: ' + answer);
            }
            else {
                answer = 'false';
            }

            return answer;
        }
        function right_answer() {
            answer_change_protect(ss);
            //answer_icon = 'test_check.gif';
             answer_icon = 'test_check.png';
            //answer_background = 'rgb(191,239,184)';
            answer_background = '#b2f1ad';
            answer_border = "solid 1px #e4f5e2";
            
            right_answers++;
        }
        function wrong_answer() {
            answer_change_protect(ss);
            //answer_icon = 'test_minus.gif';
            answer_icon = 'test_minus.png';
            //answer_background = 'rgb(255,178,178)';
            answer_background = '#ffc3c3';
            answer_border = "solid 1px #fbd8d7";
        }
        function not_answered() {
            $(ssId).css({
                "border":"0",
                "margin-top":"3px",
                "margin-bottom":"3px",
                "margin-left":"0",
                "background-color":"#F6F6F6"
            });
            
            $(ssId)
                    .append('<span style="padding-left:31px;font-size:18px;font-family:Helvetica">Ši užduotis nebuvo atlikta.</span>')
                    .css('height', 'auto');
            //answer_icon = 'test_minus.gif';
            answer_icon = 'test_minus.png';
            //answer_background = 'rgb(255,178,178)';
            answer_background = '#ffc3c3';
            answer_border = "solid 1px #fbd8d7";
        }
        function answer_change_protect(ss) {
            var change_protection = ss + '_change_protection';

            $('#' + ss)
                    .append('<div id="' + change_protection + '"></div>');
            $('#' + change_protection)
                    .css({
                'position': 'absolute',
                'top': '0px',
                'left': 'opx',
                'width': '1160px',
                'height': '718px',
                'z-index': '10000'
            });
        }

        var question = doContent[sectionName][slideName].question;

        $('#section' + inSection + slide)
                .before('<div class=\"top_hd_line\" id ="' + slide + '_answer" ></div>');
        
        if (i == 0){
            $("#" + slide + "_answer").addClass("print_mode_line_first");
        }

        $('#' + slide + '_answer')
                .append('<div class="answer_icon" id="question_icon_' + i + '"></div>')	//<img src="img/'+ answer_icon+'" alt=""></img>
                .append('<div class="answer_question" id="question_' + i + '">' + (+i + 1) + '. ' + question + '</div>')
                .append('<div class="answer_collapse" id="collapse_' + i + '_indicator"></div>');

        var indicator_image = 'transparent url(img/blue_arrow_down.png) no-repeat 50% 50%';
        var indicator_image_class = 'results_arrow_down';

        answer_icon = 'transparent url(img/' + answer_icon + ') no-repeat 50% 50%';

        $('#question_icon_' + i)
                .css({
            'position': 'absolute',
            'top': '0px',
            'left': '12px',
            'width': '60px',
            'height': '50px',
            'background': answer_icon
        });


        $('#' + slide + '_answer')
                .find('.answer_collapse')
                .addClass(indicator_image_class);

        $('#' + slide + '_answer')
                .css({
            'position': 'relative',
            'top': '0px',
            'left': '0px',
            //'width': '1160px',
            'width': '1281px',
            'height': '50px',
            'background': answer_background,
            //'border': '1px solid gray',
            'border': answer_border,
            'text-indent': '50px',
            'font-size': '24px',
            'line-height': '20px',
            'margin-top': '1px'
        })
                .bind('tap', function() {
            var $header = $(this);		//getting the next element
            var $slide_content = $header.next();		//open up the content needed - toggle the slide- if visible, slide up, if not slidedown.
            $slide_content.slideToggle(500, function() {
                //execute this after slideToggle is done
                //change text of header based on visibility of content div
                // text indicator
                // var indicator_text = $slide_content.is(":visible") ? "Suskleisti" : "Išskleisti";
                // $header.find('.answer_collapse').text(indicator_text);
                // image indicator
                if ($slide_content.is(":visible")) {
                    indicator_image = "blue_arrow_up.png";
                    indicator_image_class = "results_arrow_up"
                    //$header.find('.answer_question').css('font-weight', 'bold')
                    $header.find('.answer_collapse').switchClass("results_arrow_down",indicator_image_class);
                }
                else {
                    indicator_image = "blue_arrow_down.png";
                    indicator_image_class = "results_arrow_down"
                    //$header.find('.answer_question').css('font-weight', 'normal')
                    $header.find('.answer_collapse').switchClass("results_arrow_up", indicator_image_class);
                }

                //indicator_image = 'transparent url(img/' + indicator_image + ') no-repeat 50% 50%';
                
            });
        });

        $('#section' + inSection + slide)
                .slideToggle(500, function() {
            //$(this).prev().text('Išskleisti')
        });
    } 
 
    
    function append_test_report_details(total_questions, right_answers) {

        var percentage = right_answers / total_questions * 100;
        percentage = Number((percentage).toFixed(0));

        $section
                .prepend('<div id="test_details"></div><br>');

        if (typeof T0_time == 'undefined') {
            var time = '00:00';
        }
        else {
            var time = T0_time;
        }

        if (T0fullName == '') {
            T0fullName = 'Vardas nenurodytas';
        }
                //$('#test_details')
                //.append('<div class="test_title" id="test_title" ><img src="img/check.gif" alt=""></img></div>')
                //.append('<div class="test_title" id="test_title" >Testo pavadinimas' + '</div><br><br><br><br>')
                //.append('<div class="test_print" id="test_print" ><a href="javascript:printRezults();">Spausdinti rezultatus</a></div><br><br>')
                //.append('<div class="test_label" id="tester_time_label" >Atlikimo laikas:</div>')
                //.append('<div class="test_content" id="tester_time_content" >' + time + '</div>')
                //.append('<div class="test_label" id="tester_name_label" >Atliko: </div>')
                //.append('<div class="test_content" id="tester_name_content" >' + T0fullName + '</div><br>')
               // .append('<div class="test_label" id="answers_statistics_title">Iš viso teisingų:</div>')
                //.append('<div class="test_content" id="answers_statistics_label">' + right_answers + ' iš ' + total_questions + ' (' + percentage + '%)</div><br>');

                $("#test_details").append("<a class='top_res_link' id='print_mode_link' href='javascript:enablePrintMode();'>Spausdinimo versija</a>");
                $("#test_details").append("<a class='top_res_link' id='print_rezults_link' href=\"javascript:printRezults();\">Spausdinti rezultatus</a>");
         $('#test_details').append("<table class='test_top_desc'><tr><td colspan='3' class='rez_header'>Testo rezultatai</td></tr><tr><td class='comp_time'>Atlikimo laikas: "+time+"</td><td class='all_qw'>Iš viso teisingų: "+ right_answers + " iš " + total_questions + " (" + percentage + "%)"+"</td><td class='test_auth'>Atliko: "+T0fullName+"</td></tr></table>");

         $(".slide").addClass("slidesRes");
         $("body").css({
             "background-color":"#f6f6f6"
         });
            
        
         $('.test_print')
                .css({
            'float': 'left',
            'height': '20px',
            'text-indent': '30px',
            'font-size': '20px',
            'width': '500px',
            'display': 'block',
        });
        
        $('.test_title')
                .css({
            'float': 'left',
            'height': '50px',
            'text-indent': '30px',
            'font-size': '30px'
        });

        $('.test_label')
                .css({
            'float': 'left',
            'width': '200px',
            'line-height': '33px',
            'text-indent': '30px',
            'font-size': '24px',
            'display': 'block',
            'clear':'both'
        });

        $('.test_content')
                .css({
            'line-height': '33px',
            'font-size': '24px',
            'display': 'inline',            
        });

    }
    function answer_css() {
        $('.answer_question')
                .css({
            'position': 'absolute',
            'top': '0px',
            //'left': '50px',
            'left': '73px',
            //'width': '1100px',
            'width': '1150px',
            'height': '50px',
            'text-indent': '0px',
            'font-size': '18px',
            'line-height': '50px',
            'font-family':'Helvetica'
        });

        $('.answer_collapse')
                .css({
            'position': 'absolute',
            'top': '0px',
            'right': '0px',
            'width': '80px',
            'height': '50px',
            'text-indent': '0px',
            'font-size': '24px',
            'line-height': '50px'
        });
    }
    function remove_unnecessary() {
        $('#slidesContainer').unbind('mousewheel');
        $(document).unbind('keyup');
        $('#pageContainer').remove();
    }
}

console.log('player.js;');

// change all global variables from this "inSection" to this "_inSection" for better undertanding
var numberOfSlides = new Array();
var totalSlides = 0;
var numberOfSections = 0;
var inSection = 0;
var inSlide = 0;

console.log('numberOfSlides:');
console.log(numberOfSlides);
console.log('totalSlides=' + totalSlides);
console.log('numberOfSections=' + numberOfSections);
console.log('inSection=' + inSection + '; inSlide=' + inSlide);


var slideWidth = 1160;
var slideHeight = 718;
//var slideWidth = 580;
//var slideHeight = 359;
var slideWidthMap = "100";
var slideHeightMap = "60";

// global set width and height used at this moment
var setWidth = 1160;
var setHeight = 718;

function seName() {
    var s = 'section' + (inSection + 1);
    return s;
}
function slName() {
    var s = 'slide' + (inSlide + 1);
    return s;
}




var animatedellay = 10; // slide and navigation windom animation move dellay/speed
var mapClick = false;  // map turned off-false, map turned on true
var autoplayOn = false;

// Remove scrollbar in JS
$('#slidesContainer').css({
    'overflow': 'hidden'
});

// Insert controls in the DOM

$('#slideshow').addClass("test_slideshow");

$('#slideshow')
        .append('<div class="allControls" id="allControls"></div>');
$('#allControls')
        .append('<div class="control" id="fullscreen"></div>')
        .append('<div class="control upControlDis" id="upControl" ></div>')
        .append('<div class="control" id="downControl" ></div>')
        .append('<div class="control" id="timerControl" >00:00</div>')
        //.append('<div class="scrollbar"><div class="track"><div class="thumb"><div class="end"></div></div></div></div>');
        
         
$("#fullscreen").append('<img class="disabled" src="img/fullscreen_disabled.png" alt="" />')
            .append('<img class="normal" src="img/fullscreen.png" alt="" />')
            .append('<img class="over" src="img/fullscreen_over.png" alt="" />')
            .append('<img class="active" src="img/fullscreen_active.png" alt="" />');
    
    
// Create event listeners for .controls clicks and overs
$('#fullscreen img.normal').css('opacity', '1');
$('#fullscreen')
.bind('click', function() {
})
.bind('mouseenter', function() {
   animateControlOverOn('#fullscreen');
})
.bind('mouseleave', function() {
   animateControlOverOff('#fullscreen');
});
    

var taskNoCreated = false;
function manageSectionNumbers() {       // show section numbers
    console.log('manageSectionNumbers()');

    if (inSection == 0) {
    }
    else {
        if (taskNoCreated == false) {
            $('#sectionNumbers')
                    .append('<div id="taskNoLight"></div>');

            console.log('taskNoCreated=' + taskNoCreated);
            console.log('taskNoCreated=' + taskNoCreated);
            for (var i = 1; i < numberOfSlides[inSection] + 1; i++) {
                $('#sectionNumbers')
                        .append('<div class="taskNumber" id="taskNumber' + i + '">' + i + '</div>');
                $('#taskNumber' + i)
                        .bind('tap', function() {

                    inSlide = $(this).text() - 1;





                    moveSlide();
                });
            }
            $('#taskNumber1').addClass('taskNumber_active');
             setActiveItem(1);        
             
            
            if (i > 8){
                $("#scrollControl").css("display", "block"); //show scrollbar
            }
           
            wrapSectionNo();
            taskNoCreated = true;
            
            
            
            
            
            
        }
    }
//	$('#sectionNumbers').text(text);
testScrollBar = $("#test_scrollbar");
testScrollBar.tinyscrollbar();

}

var lastH = 0;

var marginTopShift = 0;

function setActiveItem(cTest){
    if ($("#finish_button").length > 0){
        $("#taskNumber" + cTest).css("color","black");
    }
}

function disableUpDown(cTest){
    var elLen = $("#sectionNoInner .taskNumber").length;
    
     if (cTest == 1){
        $("#upControl").addClass("upControlDis");
     }else if (cTest > 1){
        $("#upControl").removeClass("upControlDis");
     }    
     
     if (cTest == elLen){
         $("#downControl").addClass("downControlDis");
     }else if (cTest < elLen){
          $("#downControl").removeClass("downControlDis");         
     }
     //alert();
     
    
    
}

function taskNumbersMove(direction) {
    var scr = testScrollBar.data("plugin_tinyscrollbar");
    var cTest = inSlide + 1;       
            
    
    
    
    //alert(inSlide + 1);    
    //testsList[inSlide + 1] =  "no_show";
    
    //$('#taskNumber' + cTest).addClass('taskShow');
    // alert(direction);
    // alert("numberofslides:"+(numberOfSlides[inSection]));
    $('.taskNumber').removeClass('taskNumber_hover');
    $('#taskNumber' + inSlide - 1).addClass('taskNumber_hover');
    var currS = inSlide + 1;

    // marginTop min = 0, max 7*52 = 364
    var h = inSlide * 52; // calculate how much is differnet new number in heigh

    /*
     $('#sectionNoInner').animate(
     {'marginTop' : -h},
     animatedellay,
     function() {// Animation complete.
     }
     );
     */
    //alert("inSlide:" + inSlide + "counter:" + downCounter);
//$(".taskNumber").removeClass("taskNumber_active");
    if (inSlide < (8 + downCounter) && currS > downCounter) {
        var m = inSlide * 52 - marginTop;

        
        $('#taskNoLight').animate({'marginTop': m}, animatedellay, function() {
            //alert(cTest);
            disableUpDown(cTest); 
            
            
            //$('#taskNumber' + cTest).addClass('taskShow');
            setActiveItem(cTest);
            $(".taskNumber").removeClass("taskNumber_active");
            $('#taskNumber' + cTest).addClass('taskNumber_active');
            
        });
    }

   // alert(direction);
   // alert(inSlide + 1);
    
    //if ((inSlide + 1) > 8 && direction == "down") {
    if (currS > (8 + downCounter) && direction == "down") {
  // alert("move:"+(downCounter + currS) + "currS:"+ currS);
      //if (currS == (downCounter + currS)  && direction == "down") {
        downCounter++;
        //var marginTop = 52*(7-inSlide);
        
        marginTop += 52;
        scr.update(marginTop, animatedellay);
        // marginTop = marginTop + parseInt($('#sectionNoInner').css("marginTop"),10);
        
        $('#sectionNoInner').animate({'marginTop': -marginTop}, animatedellay, function() {  
              disableUpDown(cTest); 
             // marginTop += 52;
              //downCounter++;
              //$('#taskNumber' + cTest).addClass('taskShow');
              setActiveItem(cTest);
              $(".taskNumber").removeClass("taskNumber_active");
              $('#taskNumber' + cTest).addClass('taskNumber_active');      
              
        });
        //alert(marginTop);      
    }

    // alert("inSlide:"+ inSlide + "df:"+downCounter);
    if (currS == downCounter && direction == "up") {
        downCounter--;
        //var marginTop = 52*(7-inSlide);
        marginTop -= 52;   
        scr.update(marginTop, animatedellay);
        $('#sectionNoInner').animate({'marginTop': -marginTop}, animatedellay, function() {
             // downCounter--;
             //$('#taskNumber' + cTest).addClass('taskShow');
             disableUpDown(cTest); 
            setActiveItem(cTest);
             $(".taskNumber").removeClass("taskNumber_active");
             $('#taskNumber' + cTest).addClass('taskNumber_active');
             //scr.update(marginTop);
        });
         //alert(marginTop);
         //scr.update(marginTop);
    }
}

// Wrap all test .slides number with #sectionNoInner div
function wrapSectionNo() {
    //section.unwrap();
    $('.taskNumber').wrapAll('<div id="sectionNoInner" class="overview"></div>');
    $('#sectionNoInner').css('width', 52 * numberOfSlides[inSection]);
    console.log("wrap setWidth=" + 52);
    console.log("All test section slide numbers wrapped! Slides = " + numberOfSlides[inSection] + "; setWidth= " + 52 + "; Total width= " + (52 * numberOfSlides[inSection]));
}




// move test slide number indication
function moveSlideIndication() {

    // Move sectionInner using margin-left
    if (mapClick) {                                     // if map on 
        var moveDiv = '#navigateWindow';                 // set what to move
        var marginLeft = slideWidthMap * (+inSection);    // set move from left
        var marginTop = slideHeightMap * (+inSlide);      // set move from top 
    }
    else {                                               // if map off
        var moveDiv = '#sectionInner';                     // set what to move
        var marginLeft = slideWidth * (-inSection);       // set move from left
        var marginTop = slideHeight * (+inSlide);         // set move from top 
    }
    //  animate navigator or sectionInner
    // animate section left or right
    $(moveDiv).animate(
            {'marginLeft': marginLeft},
    animatedellay,
            function() {// Animation complete.
            }
    );
    //  animate section up or down
    $('.section').slice(inSection, inSection + 1).animate(
            {'marginTop': -marginTop},
    animatedellay,
            function() {
                //console.log("After move set left,right sections to 0 position");
                $('.section').slice(inSection - 1, inSection).animate(
                        {'marginTop': 0},
                0,
                        function() {// Animation complete.
                        }
                );
                $('.section').slice(inSection + 1, inSection + 2).animate(
                        {'marginTop': 0},
                0,
                        function() {// Animation complete.
                        }
                );
            }
    );
    console.log("Move to: inSection=" + inSection + "; inSlide=" + inSlide);
    manageControls();
    runSlideScript();
}






// change slidescontainer map view
function mapOn() {
    moveHome();
    setWidth = slideWidthMap;
    setHeight = slideHeightMap;
    resizeSlides();
    navigateWindow();
    mapClick = true;
    //	$('img').css({'border': 'solid 1px #aaaaaa'});
    //	$('.section').css({'border': 'solid 1px #0000aa'});
}
function mapOff() {
    $('#navigateWindow').remove();
    setWidth = slideWidth;
    setHeight = slideHeight;
    resizeSlides();
    mapClick = false;
}
function resizeSlides() {           // resize all slides to given width and height
    $('img').css({'width': setWidth, 'height': setHeight});
    $('.section').css({'width': setWidth, 'height': setHeight * 5, 'margin': '0'});
    $('.slide').css({'width': setWidth, 'height': setHeight, 'margin': '0'});
    $('#sectionInner').css('width', setWidth * numberOfSections);
    $('#sectionInner').css('height', setHeight * 5);
}
function navigateWindow() {
    console.log("NavigatorWindow created.");
    $('#sectionInner')
            .append('<div class="navigateWindow" id="navigateWindow"></div>');
    $('#navigateWindow').css({
        "position": "absolute",
        "border": "solid 1px #FF0000",
        "width": slideWidthMap,
        "height": slideHeightMap,
        "-webkit-box-shadow": "0 0 60px #333"
    });
}

// move slide to a possition and manage controls
function moveSlide(direction) {
    $('#downControl').show();
    $('#upControl').show();
    taskNumbersMove(direction);

    var moveDiv = '#sectionInner';                     // set what to move
    var marginLeft = slideWidth * (-inSection);       // set move from left
    var marginTop = slideHeight * (+inSlide);         // set move from top 

    //  animate navigator or sectionInner
    // animate section left or right
    $(moveDiv).animate(
            {'marginLeft': marginLeft},
    animatedellay,
            function() {// Animation complete.
            }
    );
    //  animate section up or down
    $('.section').slice(inSection, inSection + 1).animate(
            {'marginTop': -marginTop},
    animatedellay,
            function() {
                //console.log("After move set left,right sections to 0 position");
                $('.section').slice(inSection - 1, inSection).animate(
                        {'marginTop': 0},
                0,
                        function() {// Animation complete.
                        }
                );
                $('.section').slice(inSection + 1, inSection + 2).animate(
                        {'marginTop': 0},
                0,
                        function() {// Animation complete.
                        }
                );
            }
    );
    console.log("Move to: inSection=" + inSection + "; inSlide=" + inSlide);
    manageControls();
    //runSlideScript();

    sectionName = 'section' + inSection;
    slideName = 'slide' + inSlide;
    ss = sectionName + slideName; // section and slide name
    ssId = '#' + ss; // section and slide name
    console.log('JSF moveSlide() ss:' + ss);

    runSlideScript_template(doContent);
}


// on slide show, look for slide script and load it if it exists
var slideScriptCheck = {}; // object to track if slide script was loaded or not
function runSlideScript() {
    console.log('function runSlideScript(){}');
    var sectionName = 'section' + (inSection + 1);
    var slideName = 'slide' + (inSlide + 1);

    var slideObj = doContent[sectionName][slideName];
    var script = slideObj['script'];

    console.log(slideObj);
    console.log('script=' + script);

    if (script) {	// check is there a script available
        slideScriptCheck[sectionName + slideName];
        console.log('slideScriptCheck[sectionName+slideName]=' + slideScriptCheck[sectionName + slideName]);
        if (slideScriptCheck[sectionName + slideName]) {
            // if slide script 1, scipt is loaded, do nothing
        }
        else { // else,if slide script 0, run script
            eval(script);	// run script, script variable is string with function name
            slideScriptCheck[sectionName + slideName] = 1;
        }
    }
}

// Create event listeners for .controls clicks
$('#downControl').bind('tap', function() {
    moveDown();
}).hide();
$('#upControl').bind('tap', function() {
    moveUp();
}).hide();

/*$('#slidesContainer').bind('mousewheel', function(event, delta) {
    console.log('Mousewheel delta ' + event.originalEvent.wheelDelta);
    console.log('inSection = ' + inSection + '; inSlide = ' + inSlide);
    clearTimeout($.data(this, 'timer'));
    // find out when wheel stops
    $.data(this, 'timer', setTimeout(function() {
        console.log("Haven't scrolled in 250ms!");
        //do something
    }, 250));
    if (event.originalEvent.wheelDelta > 0) {
        moveUp();
    }
    else if (event.originalEvent.wheelDelta < 0) {
        moveDown();
    }
    else {
        //console.log("mousewheel begining or end");  
    }
    return false;
});*/

//keyboard listeners for navigation
// PgDown, PgUp should be implemented to navigate by sections, numers should navigate by menu elements
/*
 $(document).keyup(function(e) {
 //	if (e.keyCode == 27) { Esc();}          // esc
 //	if (e.keyCode == 39) { moveRight();}    // right
 //	if (e.keyCode == 37) { moveLeft();}     // left
 if (e.keyCode == 38) { moveUp(); }      // Up
 if (e.keyCode == 40) { moveDown(); }    // Down
 //	if (e.keyCode == 36) { moveHome(); }    // Home
 //	if (e.keyCode == 35) { moveEnd();}      // End
 //	if (e.keyCode == 32) { (autoplayOn) ? autoplayOn = false :autoplay();}     // Space; if autoplayOn = true then autoplayOn false to stop autoplay function, else autoplay
 //	if (e.keyCode == 220) { (mapClick)? mapOff(): mapOn();}                  // "/" mapOn/mapOff
 });
 */

$(document).bind('keyup', function(e) {
//	if (e.keyCode == 27) { Esc();}          // esc
//	if (e.keyCode == 39) { moveRight();}    // right
//	if (e.keyCode == 37) { moveLeft();}     // left
    if (e.keyCode == 38) {
        moveUp();
    }      // Up
    if (e.keyCode == 40) {
        moveDown();
    }    // Down
//	if (e.keyCode == 36) { moveHome(); }    // Home
//	if (e.keyCode == 35) { moveEnd();}      // End
//	if (e.keyCode == 32) { (autoplayOn) ? autoplayOn = false :autoplay();}     // Space; if autoplayOn = true then autoplayOn false to stop autoplay function, else autoplay
//	if (e.keyCode == 220) { (mapClick)? mapOff(): mapOn();}                  // "/" mapOn/mapOff
});

// slide move functions
function Esc() {
    if (mapClick) {
        mapOff();
    }
    else {
        moveHome();
    }
}
function moveRight() {
    if (inSection < numberOfSections - 1) {
        inSection++;
        inSlide = 0;
        moveSlide();
    }
}
function moveLeft() {
    if (inSection > 0) {
        inSection--;
        inSlide = 0;
        moveSlide();
    }
}
function moveUp() {
    if (inSlide > 0) {          // move up
        inSlide--;
        moveSlide("up");
    }
}
function moveDown() {
    if (inSlide < numberOfSlides[inSection] - 1) {    // move down
        inSlide++;
        moveSlide("down");
    }
}
function moveHome() {
    inSection = 0;
    inSlide = 0;
    moveSlide();
}
function moveEnd() {
    inSection = numberOfSections - 1;
    inSlide = 0;
    moveSlide();
}
function autoplay() {
    autoplayOn = true;
    setTimeout(function() {
        moveDown();
        if (inSlide < numberOfSlides[inSection] - 1 || inSection < numberOfSections - 1) {
            if (autoplayOn) {
                autoplay();
            }
        }
    },
            500);
    console.log('Autoplay: inSection = ' + inSection + '; inSlide = ' + inSlide);
}

// manageControls: Hides and Shows controls depending on currentPosition
function manageControls() {
    //var myJsonString = JSON.stringify(numberOfSlides + " numberOfSections="+ numberOfSections);
    //console.log(myJsonString);

    manageSectionNumbers();
    // Hide left arrow if position is first slide
    if (inSection == 0) {
        $('#leftControl').hide();
    }
    else {
        //$("#leftControl").prop('disabled', false);
        //alert('1');
        $('#leftControl').show()
    }
    // Hide right arrow if position is last slide
    if (inSection == numberOfSections - 1) {
        $('#rightControl').hide()
    }
    else {
        $('#rightControl').show()
    }
}





//runSlideScript_template(doObj,0,0);
// on slide open, looks for slide script and load it if its exists
function runSlideScript_template(doObj) {
    console.log('JS f: runSlideScript(){}');
    section = 'section' + inSection;
    slide = 'slide' + inSlide;
    //console.log(section+' '+slide);
    var slideObj = doObj[section][slide];
    var template = slideObj.template.name;		// get template name

    var scriptObj = doObj[section][slide]['script'];

    var scriptName = scriptObj['name'];

    console.log('Template ' + template + ' script =' + scriptName);

    if (scriptName) {	// check is there a script available
        if (scriptObj['iniciated']) {
            console.log('Template script is iniciated: ' + scriptName);
        }
        else {
            console.log('Template script is not iniciated: ' + scriptName);
            console.log('Iniciating template script: ' + scriptName);

            window[scriptName](); //without eval        
            scriptObj['iniciated'] = true;
        }
    }
}



// on slide show, look for slide script and load it if it exists
var slideScriptCheck = {}; // object to track if slide script was loaded or not
function runSlideScript() {
    console.log('function runSlideScript(){}');
    var sectionName = 'section' + (inSection + 1);
    var slideName = 'slide' + (inSlide + 1);

    var slideObj = doContent[sectionName][slideName];
    var script = slideObj['script'];

    console.log(slideObj);
    console.log('script=' + script);

    if (script) {	// check is there a script available
        slideScriptCheck[sectionName + slideName];
        console.log('slideScriptCheck[sectionName+slideName]=' + slideScriptCheck[sectionName + slideName]);
        if (slideScriptCheck[sectionName + slideName]) {
            // if slide script 1, scipt is loaded, do nothing
        }
        else { // else,if slide script 0, run script
            //eval(script);	// run script, script variable is string with function name                       			
            window[script]();   //without eval      
            slideScriptCheck[sectionName + slideName] = 1;
        }
    }
}



loadContent();


// take readed slide.js objects variables and using them to construct the content in the player
function loadContent() {
    console.log(">>>>>>>>>> >>>>>>>>>> >>>>>>>>>>   loadContent Starts   >>>>>>>>>> >>>>>>>>>> >>>>>>>>>>");


    var sectionName2, // temp object for section
            slideName2;       // temp object for slides
    var sections = 0
            , slides = 0;

    numberOfSlides = [];
    totalSlides = 0;

    // read slide.js created object variable doContent with content and create sections and slides in player #slidesContainer
    // construct sections and slides from slide.js variables
    for (sectionName2 in doContent) {
        console.log("Section = " + sectionName2);
        $('#slidesContainer').append('<div class="section" id="' + sectionName2 + '"></div>');

        // create slides
        for (slideName2 in doContent[sectionName2]) {
            $('#' + sectionName2)
                    .append('<div class="slide" id="' + sectionName2 + slideName2 + '"></div>');
            $('#' + sectionName2 + slideName2)
                    .css({
                'position': "relative",
                "width": "1160px",
                "z-index": "1",
                'overflow': 'hidden'
            });
            slides++; // count slides
        }
        $('#' + sectionName2).css('height', setHeight * slides);
        numberOfSlides.push(slides);
        totalSlides += slides; // count all slides
        slides = 0;
        sections++;
    }

    numberOfSections = numberOfSlides.length;

    console.log("totalSlides = " + totalSlides);
    console.log("numberOfSlides = " + numberOfSlides);
    console.log("numberOfSections = " + numberOfSections);

    // Hide left arrow control on first load
    manageControls();

    //$(function() {
    wrapSection();
    //});
    sectionName = 'section0';

    slideName = 'slide0';

    runSlideScript_template(doContent);

    console.log("<<<<<<<<<< <<<<<<<<<< <<<<<<<<<<   loadContent Ends   <<<<<<<<<< <<<<<<<<<< <<<<<<<<<<");


}

// append slide div in section with background image
function loadSlideBackground_SS(sectionName, slideName) {
    console.log("Section Slide = " + sectionName + slideName);
    var slideContent = doContent[sectionName][slideName]['background'];
    console.log("Slide background = " + slideContent);
    $('#' + sectionName).append('<div class="slide" id="' + sectionName + slideName + '"></div>');
    $('#' + sectionName + slideName).append('<div class="slide" id="' + sectionName + slideName + 'background">' + slideContent + '</div>');

    $('#' + sectionName + slideName).css({
        'position': "relative",
        "width": "1160px",
        "z-index": "1"
    });
    $('#' + sectionName + slideName + 'background').css({
        'position': "absolute",
        "z-index": "2"
    });
}

// Wrap all .slides with #sectionInner div
function wrapSection() {

    //section.unwrap();
    $('.section').wrapAll('<div id="sectionInner"></div>').css({
        'float': 'left', // Float left to display horizontally, readjust .slides width
        'width': setWidth
    });
    console.log("wrap setWidth=" + setWidth);
    // Set #sectionInner width equal to total width of all slides
    $('#sectionInner').css('width', setWidth * numberOfSections);
    console.log("wrap setWidth=" + setWidth);
    console.log("All sections wrapped! Sections = " + numberOfSections + "; setWidth= " + setWidth + "; Total width= " + (setWidth * numberOfSections));
}

// animate control buttons states from one image to another with opacity
// controlId = control div id
// fromState = control image class change from
// toState	 = control image class change to

var animationSpeed = 500;
function animateControl(controlId, fromState, toState) {
    console.log('animateControl(): id=' + controlId + ' img' + fromState);

    $(controlId + ' img' + toState)
            .stop()
            .animate(
                    {
                        opacity: 1
                    },
            animationSpeed,
                    function() {// Animation complete.
                    }
            );
    $(controlId + ' img' + fromState)
            .stop()
            .animate(
                    {
                        opacity: 0
                    },
            animationSpeed,
                    function() {// Animation complete.
                    }
            );

}
function animateControlOverOn(controlId) {
    console.log('animateControlOverOn(): id=' + controlId);

    $(controlId + ' img.over')
            .stop()
            .animate(
                    {
                        opacity: 1
                    },
            animationSpeed,
                    function() {// Animation complete.
                    }
            );
}
function animateControlOverOff(controlId) {
    console.log('animateControlOverOff(): id=' + controlId);

    $(controlId + ' img.over')
            .stop()
            .animate(
                    {
                        opacity: 0
                    },
            animationSpeed,
                    function() {// Animation complete.
                    }
            );
}
function animateControlDisableOn(controlId) {
    console.log('animateControlDisableOn(): id=' + controlId);

    $(controlId + ' img.disabled')
            .css('opacity', '1');

    $(controlId + ' img.normal')
            .stop()
            .animate(
                    {
                        opacity: 0
                    },
            animationSpeed,
                    function() {// Animation complete.
                    }
            );
    $(controlId + ' img.over')
            .stop()
            .animate(
                    {
                        opacity: 0
                    },
            animationSpeed,
                    function() {// Animation complete.
                    }
            );
    $(controlId).css('cursor', 'default');
}

function animateControlDisableOff(controlId) {
    console.log('animateControlDisableOff(): id=' + controlId);

    $(controlId + ' img.normal')
            .stop()
            .animate(
                    {
                        opacity: 1
                    },
            animationSpeed,
                    function() {// Animation complete.
                        $(controlId + ' img.disabled')
                                .css('opacity', '0');
                    }
            );
    $(controlId).css('cursor', 'pointer');
}

function animateControlActiveOn(controlId) {
    console.log('animateControlOverOn(): id=' + controlId);

    $(controlId + ' img.active')
            .stop()
            .animate(
                    {
                        opacity: 1
                    },
            animationSpeed,
                    function() {// Animation complete.
                    }
            );
}
function animateControlActiveOff(controlId) {
    console.log('animateControlOverOff(): id=' + controlId);

    $(controlId + ' img.active')
            .stop()
            .animate(
                    {
                        opacity: 0
                    },
            animationSpeed,
                    function() {// Animation complete.
                    }
            );
}

function enablePrintMode(){
    if (printMode == 0){
        printMode = 1;
        $("body").addClass("results_print");
        $(".top_hd_line").addClass("print_mode_line");
        $("#print_rezults_link").css("visibility","visible");
        $("#print_mode_link").text("Normali versija");
        $("head").append("<link id=\"test_player_print\" media=\"print\" type=\"text/css\" href=\"css/test_player_print.css\" rel=\"stylesheet\">");
    }else{
        printMode = 0;
        $("body").removeClass("results_print");
        $(".top_hd_line").removeClass("print_mode_line");
        $("#print_rezults_link").css("visibility","hidden");
        $("#print_mode_link").text("Spausdinimo versija");
        $("#test_player_print").remove();
    }    
    
   
    
    //alert("zz");
}

