// 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
 
 */

/* $.ionSound({
 sounds: [
 "slide0section0"
 ],
 path: "content/sounds/"
 });*/

var notLoadedSounds = [];
var allSounds = [];
var gallerySounds = [];
var gallerySoundsMetro = [];
var play = false;
console.log('> player.js is iniciated;');
var questionsAnim = [];
var shapeIdCounter = 1;

var sectionName = 'section0';
var slideName = 'slide0';
var ssId = '#section0slide0'; // section and slide name
var ss = 'section0slide0'; // section and slide name
var slideNum = 1;
var slideDirection;
var slideProgress = 1;

// 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;

var hideOnArray = [];



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




var animatedellay = 700; // 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'
});


create_player_controls();
function create_player_controls() {
    // Insert controls in the DOM
    $('#slideshow')
            .append('<div class="allControls" id="allControls"></div>');
    $('#allControls')
            .append('<div class="control" id="sectionNumbers" ><span class="innerNums"><span class="currNum">0</span><img class="slash_sep" src="img/slash.png" /><span class="numberAll">0</span></span></div>')
            .append('<div class="control" id="leftControl" ></div>')
            .append('<div class="control" id="rightControl" ></div>')
            .append('<div class="control" id="upControl" ></div>')
            .append('<div class="control" id="downControl" ></div>')
            //.append('<div class="mapControl" id="mapControl" >Open frames map</div>')
            .append('<div class="control" id="fullscreen" ></div>')
            .append('<div class="control" id="menuControl" ></div>')
            .append('<div class="control" id="hideControl" ></div>')
            .append('<div class="control" id="playControl" ></div>')
            .append('<div class="control" id="stopControl" ></div>')
            .append('<div class="control" id="bullet1" ></div>')
            .append('<div class="control" id="bullet2" ></div>')
            .append('<div class="control" id="bullet3" ></div>')
            .append('<div class="control" id="bullet4" ></div>')
            .append('<div class="control" id="bullet5" ></div>');

    // Slides map control and css toggle
    //$('.mapControl').bind('click',function(){ (mapClick)? mapOff() : mapOn() }); // map control button taked out, only keyboard lefted
    $('#menuControl').bind('tap', function() {
        menuClick();
    });
    $('#hideControl').bind('tap', function() {
        hideControl();
    });
}

function shapeBoxesStatus(status) {
    //$(ssId + " .resizableShape").css("display", status); 
    $(ssId + "_shapes_container").css("display", status);
}

function appendShapeBox(appendTo, shapeWidth, shapeHeight, shapeTop, shapeLeft, shapeIdCounter) {
    var currentSectionSlide = "section" + inSection + "slide" + inSlide;
    //alert(currentSectionSlide);
    var boxId = ss + "_box_" + shapeIdCounter;
    var boxQid = "#" + ss + "_box_" + shapeIdCounter;
    $("#" + appendTo + "_shapes_container").append("<div id='" + boxId + "' class=\"resizableShape\"><div class='shape_close'></div></div>");

    $(boxQid).css({width: shapeWidth + "px", height: shapeHeight + "px", top: shapeTop + "px", left: shapeLeft + "px"});

    $(boxQid).draggable({snap: false, grid: false}); //containment: "parent"   

    $(boxQid).resizable({
        handles: 'n, e, s, w, ne, se,  sw, nw'
    });


    $(boxQid).find(".shape_close").bind("click", function() {
        $(boxQid).remove();

        if ($("#" + currentSectionSlide + " .resizableShape").length == 0) { //if all shapes are removed then go to normal mode
            animateControlActiveOff('#hideControl');
            $("#" + currentSectionSlide + "_shapes_container").remove();
            hideOnArray[currentSectionSlide] = false;
            $(ssId).unbind("doubletap");
        }
    });

    /*$(boxQid).resizable({       
     handles:{ 
     'n':'',
     'e':'',
     's':'',
     'w':'#wgrip',
     'ne':'',
     'se':'',
     'sw':'',
     'nw':''}
     });*/

    shapeIdCounter++;

    return shapeIdCounter;
}

// hide squere control
var hideOn = false;		// global var

//alert(ss);
//var currentSectionSlide = "section"+inSection +"slide"+ inSlide;

//hideOnArray[currentSectionSlide] = false;

function hideControl() {
    //alert(ss);
    var currentSectionSlide = "section" + inSection + "slide" + inSlide;
    //alert(currentSectionSlide);
    //if (hideOn) {
    if (hideOnArray[currentSectionSlide]) {
        //$('#canvas2').remove();
        //init2Close();
        shapeBoxesStatus("none");
        //hideOn = false;
        hideOnArray[currentSectionSlide] = false;
        animateControlActiveOff('#hideControl');

        $(ssId).unbind("doubletap");

        if ($("#" + ss + "_shapes_container").find(".resizableShape").length == 0) {
            $("#" + ss + "_shapes_container").remove();
        }

    } else {

        //if (!("resizeAddValue" in window) || !$.browser.mozilla){
        //            resizeAddValue = 1;
        // }        

        animateControlActiveOn('#hideControl');

        $(ssId).bind("doubletap", function(e) {

            var parentOffset = $(this).offset();
            var pX = 0;
            var pY = 0;
            // $.mobile.zoom.disable(true);
            if ($.isTouchCapable()) {
                var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
                pX = touch.pageX / resizeAddValue;
                pY = touch.pageY / resizeAddValue;
            } else {
                //alert(parent.ZoomData);
                if (!$.browser.mozilla && !inFullScreenMode && parent.ZoomData != "") { //firefox don't need mul in iframe and chrome takes ZoomData from website resize
                    //resizeAddValue = parent.ZoomData;                
                    pX = e.pageX / parent.ZoomData;
                    pY = e.pageY / parent.ZoomData;

                } else {
                    pX = e.pageX / resizeAddValue;
                    pY = e.pageY / resizeAddValue;

                }


            }

            var relX = pX - parentOffset.left;
            var relY = pY - parentOffset.top;

            relX = relX - 150 / 2;
            relY = relY - 150 / 2;

            shapeIdCounter = appendShapeBox(ss, 150, 150, relY, relX, shapeIdCounter);
            //alert("x"+relX+"y:"+relY);           

            e.preventDefault();

        });

        /*$('#'+seName()+slName()).prepend('<canvas id="canvas2" width="1160" height="718"></canvas> ');                         
         $('#canvas2').css({
         'position':'absolute',
         'z-index': 9
         });*/
        //alert(ssId);

        if ($(ssId + " .resizableShape").length == 0) {
            var shapeWidth = setWidth - (30 * 2) - 2;
            var shapeHeight = setHeight - (30 * 2) - 2;
            var shapeTop = 30;
            var shapeLeft = 30;


            $(ssId).append("<div class='shapes_container' id='" + ss + "_shapes_container'></div>");

            shapeIdCounter = appendShapeBox(ss, shapeWidth, shapeHeight, shapeTop, shapeLeft, shapeIdCounter);
        } else {
            shapeBoxesStatus("block");
        }

        // if ($(ssId + " " + ".main_square_box").length == 0) {
        //  $(ssId).prepend('<div class="main_square_box" id="' + boxId + '"></div>');
        // }

        //  initDrag("canvas2");
        //init2();
        hideOnArray[currentSectionSlide] = true;
        //hideOn = true;
    }
}
// menu control
var menuOn = false;
function menuClick() {
    menuOn ? menuOn = false : menuOn = true;
    //alert(menuOn);

    memenuControl();
}

// open menu item
function memenuControl() {
    if ($('#menuList')) {
        $('#menuList').remove();
        $('#menuControl').removeClass("active");
        animateControlActiveOff('#menuControl');
    }
    if (menuOn) {
        $("#menuControl").addClass("onMenuBg");

        animateControlActiveOn('#menuControl');
        createMenuList();
    } else {
        $("#menuControl").removeClass("onMenuBg");
    }

    function createMenuList() {
        $('#slidesContainer')
                .append('<div class="menuList" id="menuList" ></div>');
        // .append('<table class="menuList" id="menuList" ></table>');

        $('#menuControl').addClass("active");

        var i = 0;
        var hr = ''; // line variable between menu items
        var s = ''; // selected section class
        // draw all menu items
        for (var menuItem in menuItems) {
            append_menu_item(menuItem);
        }
        function append_menu_item(menuItem) {
            // to draw lines between menu items one less than all items
            (i == 0) ? {} : hr = '<hr>';

            // to identify does menu item corespond to selected section, if yes, give class name selected
            (i == inSection) ? s = ' class="selected"' : s = '';


            // draw menu item
            $('#menuList')
                    .append('<div' + s + ' id="menu_item_' + i + '">' + hr + menuItems[menuItem] + '</div>');
            //.append('<tr><td' + s + ' id="menu_item_' + i + '">' + hr + menuItems[menuItem] + '</td></tr>');
            $('#menu_item_' + i)
                    .bind('click', function() {
                        var id = this.id.substr(10, 2);
                        console.log('Section id:' + id);
                        inSection = +id;
                        inSlide = 0;
                        slideNum = inSection + 1;
                        animatedellay = 0;
                        moveSlide();
                        animatedellay = 700;
                        questAnim();
                    });
            i++;
        }
    }
}
// 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"
    });
}

function changeShapeIcon() {
    var currentSectionSlide = "section" + inSection + "slide" + inSlide;

    if (hideOnArray[currentSectionSlide] != undefined) {
        if (hideOnArray[currentSectionSlide] == false) {
            animateControlActiveOff('#hideControl');
        } else {
            animateControlActiveOn('#hideControl');
        }
    } else {
        animateControlActiveOff('#hideControl');
    }
}

// move slide to a possition and manage controls
function moveSlide(direction) {
    //alert("slide:"+inSlide+ ":section:"+inSection);
    //console.log("check:",doContent["section" + inSection]["slide" + inSlide]);
    $('#playControl img.normal').css('opacity', '1');
    $('#playControl .active').css('opacity', '0');
    $("#stopControl .active").css("opacity", '0');
    play = false;

    /*for (var p = 0; p < allSounds.length; p++) { 
     $.ionSound.stop(allSounds[p]);
     }  
     
     for (var g = 0; g < gallerySounds.length; g++) { 
     $.ionSound.stop(gallerySounds[g]);
     }*/

    stopAllSounds(allSounds); //stop all sounds on slide
    stopAllSounds(gallerySounds); //stop all gallery sounds

    memenuControl();

    // remove hidesquare
    //hideOnArray[ss] ? hideControl() : {};
    //hideOn ? hideControl() : {};


    //hideControl();
    //alert(hideOnArray["section"+inSection +"slide"+ inSlide]);
    //alert(hideOnArray[ss]);

    changeShapeIcon();

    // 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 

        var prevPosHeight = (numberOfSlides[inSection - 1] - 1) * slideHeight;
    }
    //  animate navigator or sectionInner
    // animate section left or right

    // $(".questionImage").addClass("animated");
    //$(".questionImage").addClass("bounceIn");


    $(moveDiv).find(".questionImage").css({"opacity": "0", "width": "0%", "top": "50%", "left": "50%"});
    // $(moveDiv).find(".questionImage").css({"display":"none","width":"0%"});
    $(".questionImage").css({"display": "none", "opacity": "0", "width": "0%"});
    $(moveDiv).animate(
            {'marginLeft': marginLeft},
    {
        duration: animatedellay,
        start: function() {
            //start
            $(".questionImage").css({"display": "none", "opacity": "0", "width": "0%", "top": "50%", "left": "50%"}).stop();
            //$(".questionImage").css({"display":"none","opacity":"0","width":"0%"});
        },
        complete: function() {
            questAnim();

            if (direction == "right") {
                slideNum++;
            } else if (direction == "left") {
                slideNum--;
            }

            manageSectionNumbers(slideNum);

            // $('.section').slice(inSection-1,inSection).css("margin-top",-prevPosHeight);
            /*    $('.section').slice(inSection-1,inSection).animate(
             {'marginTop' : -prevPosHeight },
             0,
             function() {// Animation complete.
             }
             );*/


        }
    }

    );
    //  animate section up or down
    //console.log("GOBJ:", $('.section').slice(inSection, inSection + 1));
    $('.section').slice(inSection, inSection + 1).animate(
            {'marginTop': -marginTop},
    animatedellay,
            function() {
                //console.log("After move set left,right sections to 0 position");
                //alert(prevPosHeight);

                /* $('.section').slice(inSection-1,inSection).animate(
                 {'marginTop' : prevPosHeight },
                 0,
                 function() {// Animation complete.
                 }
                 );*/
                /*$('.section').slice(inSection+1,inSection+2).animate(
                 {'marginTop' : 0},
                 0,
                 function() {// Animation complete
                 //alert("complete");
                 }
                 );*/

                $('.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);
    //alert(ssId);

    //$(ssId).dictionary(); //dictionary init
    //$(ssId).dictionary("destroy");






    $(ssId).dictionary().dictionary("destroy");






//$("#slidesContainer").dictionary(); //dictionary init
    //$("#slidesContainer").dictionary("destroy");

    //$(document).on("load", "#slidesContainer", function() {
    //alert( "Goodbye!" ); // jQuery 1.7+
    //$(this).dictionary(); //dictionary init
    //$(this).dictionary("destroy");
    //});


    $("#slidesContainer").find(".fp-engine").each(function() {
        $(this).get(0).pause(); //stop all videos on next slide
    });


    //alert(ssId);
    //if ($(ssId).hasClass("noSound")){

    //if ($.inArray(ss, soundNames) == -1){
    //$("#playControl").unbind("click");
    //$("#stopControl").unbind("click");
    // $("#playControl img.normal").css("opacity", "0");
    //$("#playControl img.disabled").css("opacity", "1");        
    //}



    disableSound(ss);




    //$("#playControl").unbind("click");
    // $("#stopControl").unbind("click");
    // $("#playControl img.normal").css("opacity", "0");
    //$("#playControl img.disabled").css("opacity", "1");



}






// append all controls images
// each set of immages are appended in each control div and same place (overlaping) with opacity 0
// each defined in css player.js
appendControls();
function appendControls() {
    $('#fullscreen')
            .append('<img class="disabled" src="img/fullscreen_disabled.png" alt="" ></img>')
            .append('<img class="normal" src="img/fullscreen.png" alt="" ></img>')
            .append('<img class="over" src="img/fullscreen_over.png" alt="" ></img>')
            .append('<img class="active" src="img/fullscreen_active.png" alt="" ></img>');

    $('#menuControl')
            .append('<img class="disabled" src="img/menu_disabled.png" alt="" ></img>')
            .append('<img class="normal" src="img/menu.png" alt="" ></img>')
            .append('<img class="over" src="img/menu_over.png" alt="" ></img>')
            .append('<img class="active" src="img/menu_active.png" alt="" ></img>');

    $('#hideControl')
            .append('<img class="disabled" src="img/hide_disabled.png" alt="" ></img>')
            .append('<img class="normal" src="img/hide.png" alt="" ></img>')
            .append('<img class="over" src="img/hide_over.png" alt="" ></img>')
            .append('<img class="active" src="img/hide_active.png" alt="" ></img>');

    $('#playControl')
            .append('<img class="disabled" src="img/play_disabled.png" alt="" ></img>')
            .append('<img class="normal" src="img/play.png" alt="" ></img>')
            .append('<img class="over" src="img/play_over.png" alt="" ></img>')
            .append('<img class="active" src="img/play_active.png" alt="" ></img>');

    $('#stopControl')
            .append('<img class="active" src="img/stop_active.png" alt="" />');


    $('#leftControl')
            .append('<img class="disabled" src="img/left_disabled.png" alt="" ></img>')
            .append('<img class="normal" src="img/left.png" alt="" ></img>')
            .append('<img class="over" src="img/left_over.png" alt="" ></img>');

    $('#rightControl')
            .append('<img class="disabled" src="img/right_disabled.png" alt="" ></img>')
            .append('<img class="normal" src="img/right.png" alt="" ></img>')
            .append('<img class="over" src="img/right_over.png" alt="" ></img>');

    $('#upControl')
            .append('<img class="disabled" src="img/up_disabled.png" alt="" ></img>')
            .append('<img class="normal" src="img/up.png" alt="" ></img>')
            .append('<img class="over" src="img/up_over.png" alt="" ></img>');

    $('#downControl')
            .append('<img class="disabled" src="img/down_disabled.png" alt="" ></img>')
            .append('<img class="normal" src="img/down.png" alt="" ></img>')
            .append('<img class="over" src="img/down_over.png" alt="" ></img>');

    $('#bullet1')
            .append('<img class="disabled" src="img/bullet_disabled.png" alt="" ></img>')
            .append('<img class="normal" src="img/bullet.png" alt="" ></img>')
            .append('<img class="over" src="img/bullet_over.png" alt="" ></img>')
            .append('<img class="active" src="img/bullet_active.png" alt="" ></img>');
    $('#bullet2')
            .append('<img class="disabled" src="img/bullet_disabled.png" alt="" ></img>')
            .append('<img class="normal" src="img/bullet.png" alt="" ></img>')
            .append('<img class="over" src="img/bullet_over.png" alt="" ></img>')
            .append('<img class="active" src="img/bullet_active.png" alt="" ></img>');
    $('#bullet3')
            .append('<img class="disabled" src="img/bullet_disabled.png" alt="" ></img>')
            .append('<img class="normal" src="img/bullet.png" alt="" ></img>')
            .append('<img class="over" src="img/bullet_over.png" alt="" ></img>')
            .append('<img class="active" src="img/bullet_active.png" alt="" ></img>');
    $('#bullet4')
            .append('<img class="disabled" src="img/bullet_disabled.png" alt="" ></img>')
            .append('<img class="normal" src="img/bullet.png" alt="" ></img>')
            .append('<img class="over" src="img/bullet_over.png" alt="" ></img>')
            .append('<img class="active" src="img/bullet_active.png" alt="" ></img>');
    $('#bullet5')
            .append('<img class="disabled" src="img/bullet_disabled.png" alt="" ></img>')
            .append('<img class="normal" src="img/bullet.png" alt="" ></img>')
            .append('<img class="over" src="img/bullet_over.png" alt="" ></img>')
            .append('<img class="active" src="img/bullet_active.png" alt="" ></img>');
}

function checkIfGallery() {
    var info = {}
    var galType = "";
    var acc = false;
    var cSec = "section" + inSection;
    var cSld = "slide" + inSlide;
    //alert($.trim(doContent[cSec][cSld]["gallery_f"]));
    if ($.trim(doContent[cSec][cSld]["gallery"]) != "") {
        acc = true;
        galType = "thumbs";
        // info = {isGallery:acc, galType:galType}        
    }

    if ($.trim(doContent[cSec][cSld]["gallery_f"]) != "") {
        acc = true;
        galType = "metro";

    }

    info = {isGallery: acc, galType: galType}

    return info;
}

function stopAllSounds(soundsArray) {
    if (soundsArray.length > 0) {
        for (var s = 0; s < soundsArray.length; s++) {
            $.ionSound.stop(soundsArray[s]);
        }
    }
}

create_control_listeners();
function create_control_listeners() {


    // 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');
            });

    $('#menuControl img.normal').css('opacity', '1');
    $('#menuControl')
            .bind('click', function() {
            })
            .bind('mouseenter', function() {
                if (!menuOn) {
                    animateControlOverOn('#menuControl');
                }
            })
            .bind('mouseleave', function() {
                if (!menuOn) {
                    animateControlOverOff('#menuControl');
                }
            });

    $('#hideControl img.normal').css('opacity', '1');
    $('#hideControl')
            .bind('click', function() {
            })
            .bind('mouseenter', function() {
                if (!hideOn) {
                    animateControlOverOn('#hideControl');
                }
            })
            .bind('mouseleave', function() {
                if (!hideOn) {
                    animateControlOverOff('#hideControl');
                }
            });

    $('#playControl img.normal').css('opacity', '1');
    $('#playControl')
            .bind('click', function() {
                //alert(ss);
                //if (!$(ssId).hasClass("noSound")){
                var cSec = "section" + inSection;
                var cSld = "slide" + inSlide;

                var checkGallery = checkIfGallery();

                if (!checkGallery.isGallery) {

                    if (("soundNames" in window)) {
                        if (!($.inArray(ss, soundNames) == -1)) {

                            var currSound = section + slide;
                            // alert(slide + section);                

                            //$('#playControl .disabled').css('opacity', '1');                

                            if (play == false) {
                                $('#playControl .active').css('opacity', '1');
                                $('#playControl img.normal').css('opacity', '0');

                                $('#stopControl .active').css("opacity", "1");

                                $.ionSound.play(currSound);

                                play = true;
                            } else {
                                $('#playControl img.normal').css('opacity', '1');
                                $('#playControl .active').css('opacity', '0');

                                $.ionSound.pause(currSound);
                                play = false;
                            }
                        }
                    }

                } else {
                    //alert(ssId);

                    if (checkGallery.galType == "thumbs") { //thumbs gallery
                        var soundToPlay = $.trim($(ssId + " .thumbs li.selected a").data("sound_name"));
                    } else if (checkGallery.galType == "metro") { //metro gallery

                        var soundToPlay = $.trim($(ssId + "contentBig").data("sound_name"));

                        if ($(ssId + "contentBig").length == 0) {
                            if (soundToPlay == "") {
                                if (("soundNames" in window)) { //to play main section sound if added
                                    if (!($.inArray(ss, soundNames) == -1)) {
                                        soundToPlay = ss;
                                        //alert(soundToPlay);
                                    }
                                }
                            }
                        }
                    }
                    //alert(soundToPlay);
                    //console.log("check:",doContent[cSec][cSld]);
                    //console.log("sToPlay", soundToPlay);
                    if (soundToPlay != "") {
                        if (play == false) {
                            $('#playControl .active').css('opacity', '1');
                            $('#playControl img.normal').css('opacity', '0');

                            $('#stopControl .active').css("opacity", "1");

                            $.ionSound.play(soundToPlay);

                            play = true;
                        } else {
                            $('#playControl img.normal').css('opacity', '1');
                            $('#playControl .active').css('opacity', '0');

                            $.ionSound.pause(soundToPlay);
                            play = false;
                        }
                    }
                }

            })
            .bind('mouseenter', function() {
                //animateControlOverOn('#playControl');
            })
            .bind('mouseleave', function() {
                //animateControlOverOff('#playControl');
            });


    $('#stopControl')
            .bind('click', function() {
                //if (!$(ssId).hasClass("noSound")){ 
                var checkGallery = checkIfGallery();

                if (!checkGallery.isGallery) {
                    //if (!checkIfGallery()) {

                    if (("soundNames" in window)) {
                        if (!($.inArray(ss, soundNames) == -1)) {
                            $('#stopControl .active').css("opacity", "0");
                            $('#playControl img.normal').css('opacity', '1');
                            $('#playControl .active').css('opacity', '0');

                            var currSound = section + slide;
                            $.ionSound.stop(currSound);

                            play = false;
                        }
                    }

                } else {

                    if (checkGallery.galType == "thumbs") {
                        var soundToPlay = $.trim($(ssId + " .thumbs li.selected a").data("sound_name"));
                    } else if (checkGallery.galType == "metro") {
                        var soundToPlay = $.trim($(ssId + "contentBig").data("sound_name"));                        
                        
                         if ($(ssId + "contentBig").length == 0) {
                            if (soundToPlay == "") {
                                if (("soundNames" in window)) {
                                    if (!($.inArray(ss, soundNames) == -1)) {
                                        soundToPlay = ss;
                                    }
                                }
                            }
                        }                       
                    }

                    if (soundToPlay != "") {
                        $('#stopControl .active').css("opacity", "0");
                        $('#playControl img.normal').css('opacity', '1');
                        $('#playControl .active').css('opacity', '0');

                        $.ionSound.stop(soundToPlay);

                        play = false;
                    }
                }
            });


    $('#rightControl')
            .bind('tap', function(e) {
                moveRight();
            })
            .bind('mouseenter', function() {
                if (inSection != numberOfSections - 1) {
                    animateControlOverOn('#rightControl');
                }
            })
            .bind('mouseleave', function() {
                if (inSection != numberOfSections - 1) {
                    animateControlOverOff('#rightControl');
                }
            });

    $('#leftControl')
            .bind('tap', function() {
                moveLeft();
            })
            .bind('mouseenter', function() {
                if (inSection != 0) {
                    animateControlOverOn('#leftControl');
                }
            })
            .bind('mouseleave', function() {
                if (inSection != 0) {
                    animateControlOverOff('#leftControl');
                }
            });

    $('#downControl')
            .bind('tap', function() {
                moveDown();
            })
            .bind('mouseenter', function() {
                // if in last section and last slide
                if (inSection == numberOfSections - 1 && inSlide == numberOfSlides[inSection] - 1) {
                }
                else {
                    animateControlOverOn('#downControl');
                }
            })
            .bind('mouseleave',
                    function() {
                        // if in last section and last slide
                        // if ((inSection != numberOfSections - 1) && (inSlide != numberOfSlides[inSection] - 1)) {
                        // alert("insec:"+inSection+"numberOfSections:"+numberOfSections);
                        // }
                        // else {
                        // animateControlOverOff('#downControl');
                        // }
                        animateControlOverOff('#downControl');
                    });
    $('#upControl')
            .bind('tap', function() {
                moveUp();
            })
            .bind('mouseenter', function() {
                if (inSection == 0 && inSlide == 0) {
                }
                else {
                    animateControlOverOn('#upControl');
                }
            })
            .bind('mouseleave', function() {
                if (inSection == 0 && inSlide == 0) {
                }
                else {
                    animateControlOverOff('#upControl');
                }
            });

    $('#bullet1')
            .bind('tap', function() {
                inSlide = 0;
                moveSlide();
            })
            .bind('mouseenter', function() {
                animateControlOverOn('#bullet1');
            })
            .bind('mouseleave', function() {
                animateControlOverOff('#bullet1');
            });

    $('#bullet2')
            .bind('tap', function() {
                if (numberOfSlides[inSection] > 1) {
                    inSlide = 1;
                    moveSlide();
                }
            })
            .bind('mouseenter', function() {
                if (numberOfSlides[inSection] > 1) {
                    animateControlOverOn('#bullet2');
                }
            })
            .bind('mouseleave', function() {
                if (numberOfSlides[inSection] > 1) {
                    animateControlOverOff('#bullet2');
                }
            });

    $('#bullet3')
            .bind('tap', function() {
                if (numberOfSlides[inSection] > 2) {
                    inSlide = 2;
                    moveSlide();
                }
            })
            .bind('mouseenter', function() {
                if (numberOfSlides[inSection] > 2) {
                    animateControlOverOn('#bullet3');
                }
            })
            .bind('mouseleave', function() {
                if (numberOfSlides[inSection] > 2) {
                    animateControlOverOff('#bullet3');
                }
            });

    $('#bullet4')
            .bind('tap', function() {
                if (numberOfSlides[inSection] > 3) {
                    inSlide = 3;
                    moveSlide();
                }
            })
            .bind('mouseenter', function() {
                if (numberOfSlides[inSection] > 3) {
                    animateControlOverOn('#bullet4');
                }
            })
            .bind('mouseleave', function() {
                if (numberOfSlides[inSection] > 3) {
                    animateControlOverOff('#bullet4');
                }
            });

    $('#bullet5')
            .bind('tap', function() {
                if (numberOfSlides[inSection] > 4) {
                    inSlide = 4;
                    moveSlide();
                }
            })
            .bind('mouseenter', function() {
                if (numberOfSlides[inSection] > 4) {
                    animateControlOverOn('#bullet5');
                }
            })
            .bind('mouseleave', function() {
                if (numberOfSlides[inSection] > 4) {
                    animateControlOverOff('#bullet5');
                }
            });

}


// 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.
                    }
            );
}


// mouse control - wheel roll sliding
/*$('#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
});
// slide move functions
function Esc() {
    if (mapClick) {
        mapOff();
    }
    else {
        moveHome();
    }
}
function moveRight() {
    if (inSection < numberOfSections - 1) {
        inSection++;
        inSlide = 0;
        moveSlide("right");
    }
}
function moveLeft() {
    if (inSection > 0) {
        inSection--;
        inSlide = 0;
        moveSlide("left");
    }
}
function moveUp() {
    //alert("in:"+inSlide);
    //  alert("inFin:"+ (numberOfSlides[inSection-1]-1));
    // if(inSlide < numberOfSlides[inSection-1]-1){
    //if (inSlide > 0) {        // move up
    if (inSlide > 0) {

        inSlide--;




        moveSlide();
    }
    else {                       // move left

        if ((numberOfSlides[inSection - 1] - 1) > 0) {
            inSlide = numberOfSlides[inSection - 1] - 1;
            inSection = inSection - 1;
            // alert(inSlide);

            moveSlide("left");
            // moveLeft(); 

        } else {

            moveLeft();
        }
    }
}
function moveDown() {
    if (inSlide < numberOfSlides[inSection] - 1) {    // move down
        inSlide++;
        moveSlide();
    }
    else {
        moveRight();
    }
}
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() {
    //manageSectionNumbers();
    manageBullets();

    // Disable left arrow if position is first slide
    if (inSection == 0) {
        animateControlDisableOn('#leftControl');
        // if first in first section
        if (inSlide == 0) {
            animateControlDisableOn('#upControl');
        }
        else {
            animateControlDisableOff('#upControl');
        }
    }
    else {
        animateControlDisableOff('#leftControl');
        animateControlDisableOff('#upControl');
    }

    // Disable right arrow if position is last slide
    if (inSection == numberOfSections - 1) {
        animateControlDisableOn('#rightControl');
        // if last in last section
        if (inSlide == numberOfSlides[inSection] - 1) {
            animateControlDisableOn('#downControl');
        }
        else {
            animateControlDisableOff('#downControl');
        }
    }
    else {
        animateControlDisableOff('#rightControl');
        animateControlDisableOff('#downControl');
    }
}

function manageSectionNumbers(slideNum) {       // show section numbers
    //$('#sectionNumbers span').text( (inSection + 1) + '/' + numberOfSections);
    //slideNum++;

    $(".currNum").text(slideNum);
    $(".numberAll").text(numberOfSections);

    //$('#sectionNumbers span').html('<span class="currNum">'+(slideNum) + '</span><img class="slash_sep" src="img/slash.png" /><span class="numberAll">' + numberOfSections+ '</span>');
}
function manageBullets() {              // shwo hide bullets depend on section slides number
    var s = numberOfSlides[inSection];
    for (var i = 1; i < 6; i++) {
        var n = "#bullet" + i;
        if (i < s + 1) {
            animateControlDisableOff(n);
            animateControlOverOff(n);
            animateControlActiveOff(n);
        }
        else {
            animateControlActiveOff(n);
            animateControlDisableOn(n);
        }
    }

    var bulletNo = inSlide + 1;
    var n = "#bullet" + bulletNo;
    console.log("bullet%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%: " + n);
    animateControlActiveOn(n);

}






//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


            //console.log("secc:",sectionName2+slideName2);
            var snm = sectionName2 + slideName2;
            if (("soundNames" in window)) {
                if (!($.inArray(snm, soundNames) == -1)) {
                    allSounds.push(snm);
                }
            }


            if ($.trim(doContent[sectionName2][slideName2]["gallery"]) != "") {
                var gallerySlide;
                //console.log("slInfo:", doContent[sectionName2][slideName2]);
                for (gallerySlide in doContent[sectionName2][slideName2]["gallery"]["slides"]) {
                    var currSound = doContent[sectionName2][slideName2]["gallery"]["slides"][gallerySlide]["sound"]


                    if ($.trim(currSound) != "") {//alert(currSound);
                        var soundName = currSound.split("/");
                        //console.log("gslide",doContent[sectionName2][slideName2]["gallery"]["slides"][gallerySlide]);
                        gallerySounds.push(soundName[soundName.length - 1]);
                    }
                }
            }

            if ($.trim(doContent[sectionName2][slideName2]["gallery_f"]) != "") {
                var gallerySlide;
                //console.log("slInfo:", doContent[sectionName2][slideName2]);
                for (gallerySlide in doContent[sectionName2][slideName2]["gallery_f"]["slides"]) {
                    var currSound = doContent[sectionName2][slideName2]["gallery_f"]["slides"][gallerySlide]["sound"]
                    if ($.trim(currSound) != "") {//alert("in");
                        var soundName = currSound.split("/");
                        //console.log("gslide",doContent[sectionName2][slideName2]["gallery"]["slides"][gallerySlide]);
                        gallerySoundsMetro.push(soundName[soundName.length - 1]);
                    }
                }
            }




        }




        $('#' + sectionName2).css('height', setHeight * slides);
        numberOfSlides.push(slides);
        totalSlides += slides; // count all slides
        slides = 0;
        sections++;
    }

    gallerySounds = gallerySounds.concat(gallerySoundsMetro);

    console.log(gallerySounds, "metro");

    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';

    manageSectionNumbers(slideNum);

    runSlideScript_template(doContent);


    disableSound(ss);



    //alert(allSounds);
    $.ionSound({
        sounds: allSounds,
        path: "content/sounds/",
        gallerySounds: gallerySounds,
        galleryPath: "content/sounds/gallery/",
    });


    //notLoadedSounds = $.ionSound.getNotLoadedSounds();
    //alert(notLoadedSounds);   


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


}

function disableSound(ss, soundName) {
    var checkGallery = checkIfGallery();

    if (!checkGallery.isGallery) {
        //if (!checkIfGallery()) {
        if (("soundNames" in window)) {
            if ($.inArray(ss, soundNames) == -1) {
                $("#playControl img.normal").css("opacity", "0");
                $("#playControl img.disabled").css("opacity", "1");
            }
        } else {
            $("#playControl img.normal").css("opacity", "0");
            $("#playControl img.disabled").css("opacity", "1");
        }
    } else {
        var cSec = "section" + inSection;
        var cSld = "slide" + inSlide;

        if (soundName == undefined) {

            if (checkGallery.galType == "thumbs") {
                //alert(checkGallery.galType);
                if ($(ssId + " .thumbs li.selected a").length > 0) {
                    var sNm = $.trim($(ssId + " .thumbs li.selected a").data("sound_name"));
                    if (sNm == "") {
                        $("#playControl img.normal").css("opacity", "0");
                        $("#playControl img.disabled").css("opacity", "1");
                    } else {
                        $("#playControl img.normal").css("opacity", "1");
                        $("#playControl img.disabled").css("opacity", "0");
                    }
                    //alert(sNm);

                } else {
                    var fObj = firstObj(doContent[cSec][cSld]["gallery"]["slides"]);
                    if (fObj) {
                        var csName = $.trim(fObj["sound"]);
                        if (csName == "") {
                            $("#playControl img.normal").css("opacity", "0");
                            $("#playControl img.disabled").css("opacity", "1");
                        } else {
                            $("#playControl img.normal").css("opacity", "1");
                            $("#playControl img.disabled").css("opacity", "0");
                        }
                    }
                }
            } else {

                if ($(ssId + "contentBig").length > 0) {
                    var sNm = $.trim($(ssId + "contentBig").data("sound_name"));
                    if (sNm == "") {
                        $("#playControl img.normal").css("opacity", "0");
                        $("#playControl img.disabled").css("opacity", "1");
                    } else {
                        $("#playControl img.normal").css("opacity", "1");
                        $("#playControl img.disabled").css("opacity", "0");
                    }

                } else {                    
                    
                    $("#playControl img.normal").css("opacity", "0");
                    $("#playControl img.disabled").css("opacity", "1");
                    $("#playControl img.active").css("opacity", "0");
                    $("#stopControl img.active").css("opacity", "0");                    
                    
                    if (("soundNames" in window)) {
                        if ($.inArray(ss, soundNames) == -1) {
                            $("#playControl img.normal").css("opacity", "0");
                            $("#playControl img.disabled").css("opacity", "1");
                        } else {
                            //$("#playControl img.normal").css("opacity", "1");
                            //$("#playControl img.disabled").css("opacity", "0");
                            $("#playControl img.normal").css("opacity", "1");
                            $("#playControl img.disabled").css("opacity", "0");
                            $("#playControl img.active").css("opacity", "0");
                            $("#stopControl img.active").css("opacity", "0");
                        }

                    }/* else {

                        $("#playControl img.normal").css("opacity", "0");
                        $("#playControl img.disabled").css("opacity", "1");
                        $("#playControl img.active").css("opacity", "0");
                        $("#stopControl img.active").css("opacity", "0");
                    }*/                    
                }

                //$("#playControl img.normal").css("opacity", "0");
                //$("#playControl img.disabled").css("opacity", "1");
            }

        } else {
            if (soundName == "") {
                $("#playControl img.normal").css("opacity", "0");
                $("#playControl img.disabled").css("opacity", "1");
                $("#playControl img.active").css("opacity", "0");
                $("#stopControl img.active").css("opacity", "0");
            } else {
                $("#playControl img.normal").css("opacity", "1");
                $("#playControl img.disabled").css("opacity", "0");
                $("#playControl img.active").css("opacity", "0");
                $("#stopControl img.active").css("opacity", "0");
            }
        }
    }
}

function firstObj(obj) {
    var first;
    for (var i in obj) {
        if (obj.hasOwnProperty(i) && typeof (i) !== 'function') {
            first = obj[i];
            break;
        }
    }

    return first;
}

// 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));
}

