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

*/

console.log('> player.js is iniciated;');
var questionsAnim = [];

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;

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>0/0</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() });
	}
	
	// hide squere control
	var hideOn = false;		// global var
	function hideControl() {                
		if (hideOn) {
			$('#canvas2').remove();
			init2Close();
			hideOn = false;
			animateControlActiveOff('#hideControl');
		}
		else{
			animateControlActiveOn('#hideControl');
			$('#'+seName()+slName()).prepend('<canvas id="canvas2" width="1160" height="718"></canvas> ');
			$('#canvas2').css({
				'position':'absolute',
				'z-index': 9
			});
                       //  initDrag("canvas2");
			init2();
			hideOn = true
                       
		}
	}
		// menu control
	var menuOn = false;
	function menuClick() {
		menuOn ? menuOn = false: menuOn = true;
		memenuControl();
	}
	
	// open menu item
	function memenuControl() {
		if ($('#menuList')) {
			$('#menuList').remove();
			$('#menuControl').removeClass("active");
			animateControlActiveOff('#menuControl');
		}
		if (menuOn) {
			animateControlActiveOn('#menuControl');
			createMenuList();
		}
		
		function createMenuList() {
			$('#slidesContainer')
				.append('<div class="menuList" id="menuList" ></div>');
			
			$('#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>');
				$('#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;
						});
				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"
		});
	}      

        // move slide to a possition and manage controls
	function moveSlide(direction) {
		//alert("slide:"+inSlide+ ":section:"+inSection);
            
            memenuControl();
		
		// remove hidesquare
		hideOn ? hideControl() : {} ;
		
		// 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);                       
                
                $("#slidesContainer").dictionary(); //dictionary init
                $("#slidesContainer").dictionary("destroy");
                
                $("#slidesContainer").find(".fp-engine").each(function(){
                    $(this).get(0).pause(); //stop all videos on next slide
                });
                
	}
	
		
	
	
	
	
	// 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>');
		
		
		$('#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>');
	}	
	
	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(){})
		.bind('mouseenter', function(){ animateControlOverOn('#playControl'); })
		.bind('mouseleave', function(){ animateControlOverOff('#playControl');});
	
	$('#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)){}
				else{ 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++;
                $('#sectionNumbers span').text((slideNum) + '/' + numberOfSections);
	}
	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
        }
        $('#' + 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';
        
        manageSectionNumbers(slideNum);
	
	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));
}

