/*
Home Page Slider Code Full Screen Version
By Brendon Irwin
Sandbox Software Solutions
Last Update: Jan 4th 2012
*/

(function($) {/*Mouse Code Determination*/
var types = ['DOMMouseScroll', 'mousewheel'];
$.event.special.mousewheel = {
    setup: function() {
        if ( this.addEventListener ) {
            for ( var i=types.length; i; ) {
                this.addEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = handler;
        }
    },
    teardown: function() {
        if ( this.removeEventListener ) {
            for ( var i=types.length; i; ) {
                this.removeEventListener( types[--i], handler, false );
            }
        } else {
            this.onmousewheel = null;
        }
    }
};
$.fn.extend({
    mousewheel: function(fn) {
        return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
    },

    unmousewheel: function(fn) {
        return this.unbind("mousewheel", fn);
    }
});
function handler(event) {
    var orgEvent = event || window.event, args = [].slice.call( arguments, 1 ), delta = 0, returnValue = true, deltaX = 0, deltaY = 0;
    event = $.event.fix(orgEvent);
    event.type = "mousewheel";
    // Old school scrollwheel delta
    if ( event.wheelDelta ) { delta = event.wheelDelta/120; }
    if ( event.detail     ) { delta = -event.detail/3; }
    // New school multidimensional scroll (touchpads) deltas
    deltaY = delta;
    // Gecko
    if ( orgEvent.axis !== undefined && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
        deltaY = 0;
        deltaX = -1*delta;
    }
    // Webkit
    if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY/120; }
    if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = -1*orgEvent.wheelDeltaX/120; }
    // Add event and delta to the front of the arguments
    args.unshift(event, delta, deltaX, deltaY);
    return $.event.handle.apply(this, args);
}
})(jQuery);


$(function(){
	function getWindowWidth() {
	  var myWidth = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
	  }
	 return myWidth -20; //scroll bars!
	}

	function getWindowHeight() {
	  var myHeight = 0;
	  if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myHeight = window.innerHeight;
	  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		myHeight = document.documentElement.clientHeight;
	  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		myHeight = document.body.clientHeight;
	  } 
	  return myHeight;
	}
	var isiPad = 0;
	if ( (navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1) ){
		isiPad = 1;
	}
	
	var AnimEnabled =  1;
	
	if( $('#HomePageSlider').length != 0){
		
		$('#HomePageSlider').focus();  
		
		function log(  text ){
			//console.log(text); //comment this out or IE will not be happy
		}

		var ww = getWindowWidth();
		var curSliderBarWidth = 138; 
		var newSliderBarWidth = 0;
		
		$('#OuterPageFullSpan').width( ww );
		$('#OuterPageFullSpan').height(460);
		
		$('#sliderWrap, #HomePageSlider').width( ww );
		
		$('#sliderWrap').append('<div style="position: absolute; z-index: 10000; left: ' + ((ww-16)/2) +'px; top: ' + ((460 -32) /2) +'px; display: none; background-color: #fff;" id="loadAnimation"><img height="32" width="32" src="/GetSiteFile/ajax-loader.gif"/></div>');
		
		$('#sliderBar').width( ww - curSliderBarWidth - 40);

		var maxVisibleItems = Math.ceil( ww / 710 );
			//log( ww + " is the width  / 710 = " );
		var itemsPerScroll = maxVisibleItems;
			//log( maxVisibleItems + " should be shown on this screen");
		
		var briefText = "";
		var buttonText = "";
		var buttonLink = "";
		var count = 0; 
		$('.listModule_tId_4 .listRow').each(function(){
			briefText = ""; buttonLink = "";  buttonText = "";
			if( !$(this).hasClass('listRowAdd') ){
				briefText =  $(this).find('.listData_12 .value').html();
				buttonLink = $(this).find('.listData_14 .value a').attr('href');
				buttonText = $(this).find('.listData_15 .value').html();
				$(this).append('<div id="project_' + count + '" class="projectBlackOverlay"><span class="projectDescription">' + briefText + '</span><a class="projectButton" href="' + buttonLink +'">' + buttonText + '</a>');
				if( $.trim(buttonText) == ""){ $('#project_' + count + ' .projectButton').css('display', 'none'); }
				
				
				if( count >= maxVisibleItems && isiPad == 0){ $(this).css('display' , 'none'); } //hide images out side of chats
				count++;
			}
		});
		
		$('#HomePageSlider .listModule_tId_4').width( (maxVisibleItems * 710) ); /*700 width + 10 margin*/
		var currentSpot = 0;
		
		function animateSlider(){
			checkScroll();
			$('#HomePageSlider .listModule_tId_4').stop();
			$('#HomePageSlider .listModule_tId_4').animate({
				left: -1 * ((currentSpot / maxVisibleItems) * ( (maxVisibleItems * 710) - ww ) )
			}, 500, function() {
				$('#HomePageSlider .listModule_tId_4').stop();
			});
		}
		
		function checkScroll()
		{	
			if( currentSpot == maxVisibleItems && count != maxVisibleItems)
			{
				AnimEnabled = 0; 
				
				$('#loadAnimation').css('display','block');
				if( (maxVisibleItems + itemsPerScroll)  > count)
				{
						maxVisibleItems = count;	
				}else
				{
					maxVisibleItems = maxVisibleItems + itemsPerScroll;
				}
				
				$('#HomePageSlider .listModule_tId_4').width( (maxVisibleItems * 710) );
				$('.listModule_tId_4 .listRow').each(function(index){ if( !$(this).hasClass('listRowAdd') ){ if( index <= maxVisibleItems ){ $(this).fadeIn(2500, function() { });  } } });
				newSliderBarWidth =  ((( 100 - ((maxVisibleItems / count ) * 50)  ) /100 ) * curSliderBarWidth );
				$('#sliderBar').width(  $('#HomePageSlider').width() - newSliderBarWidth - 40);		
				$("#sliderBar").slider({ min: 0, value : (maxVisibleItems - itemsPerScroll) , max : maxVisibleItems , stop: function(event, ui){ }, slide: function( event, ui ) {
					currentSpot = ui.value;
					if( AnimEnabled == 1){	animateSlider(); }
				}});
				
				$("#sliderBar").slider({ value : currentSpot });
				$('#sliderBar a').animate({
					width: newSliderBarWidth
				}, 2000, function(){ }); 
				
				AnimEnabled = 1; 
				$('#loadAnimation').fadeOut(500, function () {  });		
			}
		}
		
		$("#sliderBar").slider({
			value:0,
			min: 0,
			max: maxVisibleItems, 
			step: .5 ,
			slide: function( event, ui ) {
				currentSpot = ui.value;
				if( AnimEnabled == 1){	animateSlider(); }
			},	
			stop: function(event, ui){

			}	
		});
		$('#sliderBar a').append('<span id="rightArrow"></span>');
		$('#rightArrow').css({'float' : 'right', 'background-image' : 'url(/GetSiteFile/sliderbar.png)','background-position' : 'right', 'overflow' : 'hidden', 'width' : '20px', 'height' : '21px', 'display' : 'block'});
		
		/*Arrow Key Press*/
		$(document).keydown(function(e){
			if (e.keyCode == 37) { 
				if( currentSpot > 0){
					if( AnimEnabled == 1){
						currentSpot = currentSpot - .5;
						$( "#sliderBar" ).slider({ value : currentSpot });
						animateSlider();
					}
				}
				return false;
			}
			if (e.keyCode == 39) { 
				if( currentSpot < maxVisibleItems){
					if( AnimEnabled == 1){
						currentSpot = currentSpot + .5;
						$( "#sliderBar" ).slider({ value : currentSpot });
						animateSlider();
					}
				}
				return false;
			}
		});
		/*Mouse Wheel Slide*/
		$('#OuterPageFullSpan').mousewheel(function(event, delta) {
         var val = currentSpot;
			if (delta > 0){
				if( currentSpot < maxVisibleItems){
					if( AnimEnabled == 1){
						currentSpot = currentSpot + .5;
						$( "#sliderBar" ).slider({ value : currentSpot });
						animateSlider();
					}
				}
			}else{
				if( currentSpot > 0){
					if( AnimEnabled == 1){
						currentSpot = currentSpot - .5;
						$( "#sliderBar" ).slider({ value : currentSpot });
						animateSlider();
					}
				}
			}
             return false; // prevent default
		});

		
		if( isiPad == 1){
			//its an iDevice
			$('#sliderBar').css('display', 'none'); // hide the slider
			$('#HomePageSlider .listModule_tId_4').width( (count * 710) ); //all items should be visible
			$('#HomePageSlider').css({'position' : 'absolute', 'overflow-y': 'hidden', 'overflow-x' : 'scroll', 'z-index' : '1', 'height' : '450px'});
			
			//$('#HomePageSlider').content().wrap('<div id="iPadWrap"></div>');
			$('#HomePageSlider .listModule_tId_4').css({'position' : 'relative'});
			var myScroll;
			function loaded() {
				myScroll = new iScroll('HomePageSlider', {  scrollbarClass: 'myScrollbar', fadeScrollbar: true, fixedScrollbar: true, hideScrollbar: false });
			}
			
			document.addEventListener('DOMContentLoaded', loaded, false);	
						
		}
			
			
		
		/* Dynamic Window Resizing*/
		window.onresize = function(event) {
			ww = getWindowWidth();
			$('#OuterPageFullSpan').width( ww );
			$('#sliderWrap, #HomePageSlider').width( ww );
			$('#sliderBar').width( ww - curSliderBarWidth - 40);
			itemsPerScroll = Math.ceil( ww / 710 );
		}
	}
});
