var welcome = true;
var secondsOffset = 675;
var typeHolder, welcomeWDObj, listOfIconsObj, listOfSlidesObj, slideHolderObj, slideContentObj, slideLeftBtnObj, slideRightBtnObj, answerObj, currentType;
var slideWidth = 700;//$('#slideHolder').width(); // should be able to use this, but can't b/c the document isn't ready. Need to restructure it a bit.
var totalSlideWidth = 0;
var totalSlides = 0;
var currentSlide = 1;	//starts at 1 (due to the fact that nth-child starts at 1)
//hard coding the images paths, not sure how else to do it.
var preloadImagesArr = new Array( 
	"/wp-content/themes/WD/images/home/img_icon_crayon_over.png",
	"/wp-content/themes/WD/images/home/img_icon_puzzle_over.png",
	"/wp-content/themes/WD/images/home/img_icon_toolbox_over.png",
	"/wp-content/themes/WD/images/home/img_icon_wheel_over.png"
);

$(document).ready(function() {
    preLoadImages(preloadImagesArr);

    hideAllContent();
    //start the show
	registerObjects();
	calculateLists();
	setupIconControls();
	startIntro();
});

/* toggleOpacity - show or hide something using opacity if possible
 * obj = jquery object to manipulate, required
 * options = object containt the following
 *   toggle = boolean, true to show false to hide, defaults to true
 *   m = mutliplier of time, defaults to 1
 *   callback = the callback function passed through to the animation
 */
function toggleOpacity( obj, options ) {
    if ( typeof options != 'undefined' ) {
        if ( typeof options['m'] == 'undefined' ) options['m']= 1;
        if ( typeof options['toggle'] == 'undefined' ) options['toggle'] = true;
    } else {
        options = { toggle: true, m: 1 } ;
    }
    var callback = function() { if (typeof options['callback']  == "function") options.callback() };
    if ( $( 'html' ).is('.opacity') ) {
        if ( options['toggle'] ) {
            obj.animate( { opacity: 1 }, ( options['m'] * secondsOffset ), options.callback );
        } else {
            obj.animate( { opacity: 0 }, ( options['m'] * secondsOffset ), options.callback );
        }
    } else {
        if ( options['toggle'] ) {
            obj.show( 0, options.callback );
        } else {
            obj.hide( 0, options.callback );
        }
    }
}

//grab objects
function registerObjects()
{    
    //get our Objects
    welcomeWDObj 		= $('#welcome_warren-douglas');
    listOfIconsObj 		= $('#controlList ul li');
    listOfSlidesObj 	= $('#slideContent ul li');
    slideHolderObj 		= $('#slideHolder');
    slideContentObj 	= $('#slideContent');
    slideLeftBtnObj 	= $('#slideLeft');
    slideRightBtnObj 	= $('#slideRight');
    answerObj 			= $('#answerHolder');
}

function calculateLists()
{
   	$('#slideHolder ul').each(function() {
    	totalSlideWidth = 0;
    	$(this).find('li').each(function() {
    		totalSlideWidth += $(this).width();
    		//add px per slide for padding, multiply it by 2 (padding on both sides)
    		//totalSlideWidth += (28 * 2);
    	});
    	$(this).width(totalSlideWidth);
	});
}

function startIntro()
{
	//start with WD text
    toggleOpacity(slideLeftBtnObj, { toggle: false, m:0 });
    toggleOpacity(slideRightBtnObj, { toggle: false, m:0 });
    toggleOpacity( welcomeWDObj, { m: 2 } );
	listOfIconsObj.each(function() {
        toggleOpacity( $(this), { m: 2 } );
	});
}

function prepareSlider(type)
{
	slideContentObj.css('left', '0px');
}

function setupIconControls()
{
    // instead of doing this block for each, 
    // loop through a jquery object of elements, get the id and pass it to init
    listOfIconsObj.click( function(e) {
        e.preventDefault;
        initContent($(this).attr('id'));
        clearActiveStates();
        $(this).find('a').addClass('active');
    });
}

function initContent(type)
{
	if(currentType == type) {
		//refrain from doing anything, we're on the current section
	} else {
		currentType = type;
	    typeHolder = type;
		if(welcome == true) {
			outroWelcome(type);
			prepareSlider(type);
			hideAllContent();
			$('#' + type + 'Content').show();
			welcome = false;
		} else {
			//fade out current content (Q & A)
            toggleOpacity( slideContentObj, { toggle: false, m: 0.5, callback: function() {
			    //update Q & A
	    		answerRef = getAnswerRef(type, 1);
				initAnswer(answerRef);
	    		prepareSlider(type);
	    		hideAllContent();
	    		$('#' + type + 'Content').show();
			} } );
			//fade back in 
            toggleOpacity( slideContentObj ); // there use to be a delay of 1.5 added in, no longer used.
		}
		//get number of slides
		totalSlides = getTotalSlides(type);
		if(totalSlides <= 1) {
			disableSliderControls();
            toggleOpacity( slideLeftBtnObj, { toggle: false } );
            toggleOpacity( slideRightBtnObj, { toggle: false } );
		} else {
            toggleOpacity( slideLeftBtnObj, { m: 0 } );
            toggleOpacity( slideRightBtnObj, { m: 0 } );
			setupSliderControls();
		}
		//reset slide key
		currentSlide = 1;
	}
}

function outroWelcome(type)
{
    toggleOpacity( welcomeWDObj, {toggle: false, m: 0.5 } );
    toggleOpacity( slideHolderObj, { m: 0 } );
    toggleOpacity( slideContentObj, {toggle: true, m: 1.5 } ); //used to be delay of 1.5 and timing of .5
		//setup the answer (first one)
		answerRef = getAnswerRef(type, 1);
		initAnswer(answerRef);
}

function setupSliderControls()
{
    // TODO Opacity sorta works here b/c the images are small with little alpha transparency
    curPos = getSliderPosition();

    if ( curPos > ( slideWidth - ( totalSlides * slideWidth ) )  ) { 
        slideRightBtnObj.css( { opacity: 1 } ) 
        slideRightBtnObj.unbind('click').click(function(e) {
            e.preventDefault;
            moveSlider("right");
        });

    } else { 
        slideRightBtnObj.css( { opacity: .2 } ) 
    };

    if ( curPos < 0 ) { 
        slideLeftBtnObj.css( { opacity: 1 } ) 
        slideLeftBtnObj.unbind('click').click(function(e) {
            e.preventDefault;
            moveSlider("left");
        });
    } else { 
        slideLeftBtnObj.css( { opacity: .2 } ) 
    };
	
	//apply cursor hand
	slideLeftBtnObj.find('a').css('cursor', 'pointer');
	slideRightBtnObj.find('a').css('cursor', 'pointer');
}

function disableSliderControls()
{
	slideLeftBtnObj.unbind('click');
	slideRightBtnObj.unbind('click');
}

function moveSlider(dir)
{
	//disable the buttons
	disableSliderControls();
	//get current 'left' position of the slider
	curPos = getSliderPosition();
	if(dir == 'left') {
		//make sure it is not the first slide, then you can move, if it is, disable stuff
		if(curPos >= 0) {
			//don't do anything
			setupSliderControls();
		} else {
			slideContentObj.animate({ 'left': '+=' + slideWidth + 'px' }, (0.5 * secondsOffset), function() {
				//once done...re-enable the buttons
				setupSliderControls();
			});	
			//update current slide
			currentSlide--;
			answerRef = getAnswerRef(typeHolder, currentSlide);
			initAnswer(answerRef);
		}
		
	} else if(dir == 'right') {
		//make sure it is not the last slide, then you can move, if it is, disable stuff
		var maxPosition = ((parseInt(slideContentObj.find('ul#' + typeHolder + 'Content').css('width')) - slideWidth) * -1);
		if(curPos <= maxPosition) {
			//don't do anything
			setupSliderControls();
		} else {
			slideContentObj.animate({ 'left': '-=' + slideWidth + 'px' }, (0.5 * secondsOffset), function() {
				//once done...re-enable the buttons
				setupSliderControls();
			});	
			//update current slide
			currentSlide++;
			answerRef = getAnswerRef(typeHolder, currentSlide);
			initAnswer(answerRef);
		}
	}
}

function initAnswer(answerRef)
{
	//fade out (if it already isn't) answer
    toggleOpacity( answerObj, { toggle: false, m: .5, callback: function() {
		//switch out image
		answerObj.html(answerRef);
		//fade back in
        toggleOpacity( answerObj, { m: .5 } ); // there was a delay of 500
	} } );
}

function getSliderPosition()
{
	return parseInt(slideContentObj.css('left'));
}

function getTotalSlides(type)
{
	var slidesNum = $('#slideContent ul#' + type + 'Content').children().length;
	return slidesNum;
}

function getAnswerRef(type, currentSlide)
{
    return $("#slideContent ul#" + type + "Content li:nth-child(" + currentSlide + ")").attr("data");
}

function hideAllContent()
{
    $('#puzzleContent').hide();
    $('#toolboxContent').hide();
    $('#wheelContent').hide();
    $('#crayonContent').hide();

}

function disableArrow(which)
{
	if(which == 'left') {
		slideLeftBtnObj.unbind('click');
		slideLeftBtnObj.find('a').css('cursor', 'default');
	} else if(which == 'right') {
		slideRightBtnObj.unbind('click');
		slideRightBtnObj.find('a').css('cursor', 'default');
	}
}

function clearActiveStates()
{
	$('#puzzle a').removeClass('active');
	$('#toolbox a').removeClass('active');
	$('#wheel a').removeClass('active');
	$('#crayon a').removeClass('active');
}

//preload images
function preLoadImages(arrayOfImages) {
    if (document.images) {
    	preload_image_object = new Image();        
    	var i = 0;
    	var arrayLen = arrayOfImages.length;
    	var images = new Array();
    	for(i=0; i<arrayLen; i++) {
        	preload_image_object.src = arrayOfImages[i];
        	images[i] = new Image();
			images[i].src = arrayOfImages[i];
        }
    }
}

