$(function(){
	
/*-----------------------------------------------------------------------*/
/* ! VAR VAR VARS */
/*----------------------------------------------------------------------*/
	var pictures			=			[]
	,	indic				=			$('.indic ul')
	,	indicWdt			=			0
	,	mainPad				=			$('.main-content').css('paddingTop')
	,	navPrev				=			$( '.arrow.previous' )
	,	navNext				=			$( '.arrow.next' )
	,	hasHov				=			false
	,	handheld			=			false
	,	tablet				=			false
	,	i					=			0
	,	hasRun				=			false
	,	len					=			0
	,	current				=			0
	,	padTestStr			=			''
	,	inc					=			0
	,	winSize				=			getWidth(1)
	,	cards				=			[]
	,	providerNames		=			[]
	,	name				=			$("h3.pro-name")
	,	nameStr				=			""
	,	nameHREF			=			""
	,	firstVisit			=			"true"
	,	sections			=			['home','providers','services','collection','contact']
	,	prov				=			false
	,	deepLink			=			false
	,	serv				=			false
	,	run					=			0
	,	runx				=			0
	,	pageWdt 			= 			$( window ).width()
	,	pageHgt 			= 			$( window ).height()
	,	pImg				=			{}
	,	redrawEvt			=			'onorientationchange' in window ? 'orientationchange' : 'resize'
	, 	pImgBg				=			[]
	,	hasBg				=			false
	,	nopacity			=			$.support.opacity;
	
/*-----------------------------------------------------------------------*/
/* ! Detect iPhone */
/*----------------------------------------------------------------------*/
	
	if(RegExp("iPhone").test(navigator.userAgent)){	
		handheld = true;
	}else if(RegExp("iPad").test(navigator.userAgent)) {
		tablet = true;
	}
	
/*-----------------------------------------------------------------------*/
/* ! Determine Current Page to set variables */
/*----------------------------------------------------------------------*/
	
	$('.goback').html(lookupSection().then).delay(200).fadeIn(220);
	
	if ($('.home').length > 0){
	
		len = $( '.imgs li' ).length;
		
		$('.goback').hide().css({'opacity':0});
		
		resizeMain();
		
		$(window).resize(function() {
			resizeMain();
		});
		
		$('.indic').prepend('<div class="tooltip">try using Your Arrow Keys to Navigate</div>');
		$('.tooltip').delay(500).fadeIn(300);
		
		if (handheld == true){
		
			$('.goto').html(lookupSection().later).delay(200).fadeIn(220).click(function() {
				window.location.href = '/'+lookupSection().later+'/';
			})
			$('.indic').hide();
			
		}
		
	}else if ($('.providers').length > 0) {
		
		prov = true;
		len = $('.card').length;
		
		
	}else if ($('.services').length > 0) {
	
		serv = true;
	
	}else if ($('.collection').length > 0) {

		len = $('.card').length;

	}else if ($('.contact').length > 0) {

		$('.subnav').hide();

	}
	
	
	if(len < 1){
		
		$('.goto').html(lookupSection().later).delay(200).fadeIn(220);
		
	}
	
	
/*-----------------------------------------------------------------------*/
/* ! Image Array & Provider Array */
/*----------------------------------------------------------------------*/
	
	$('.imgs li').each(function(){
		pictures.push({
		
			src : $( this ).attr( 'data-src' ),
			fade : 500,
		
		})
		
	});
	
/*-----------------------------------------------------------------------*/
/* ! Indicator */
/*----------------------------------------------------------------------*/

	$('.indic li').remove();
		
		for(i; i<len; ++i){
	
			indic.append('<li data-pos="'+i+'"></li>');
			indicWdt = indicWdt+$('.indic li').width()+4;
			
		}
	
	$('.indic li').click(function() {
		shiftTo($(this).attr('data-pos'))
	})
	
	indic.css({
		width: indicWdt
	});

/*-----------------------------------------------------------------------*/
/* ! Bind Vegas */
/*----------------------------------------------------------------------*/
	
	$( 'body' ).bind( 'vegasload', function(e, img){
	
		var src = $( img ).attr('src'),
			inx = $( 'a[href="' + src + '"]' ).parent( 'li' ).index();
	
	});
		
/*-----------------------------------------------------------------------*/
/* ! Vegas Stuff */
/*----------------------------------------------------------------------*/
	
	if( $('body').hasClass('home') || $('body').hasClass('contact') || $('body').hasClass('services') &&  handheld == false){
	



/////
		$.vegas( 'slideshow', {
		    backgrounds: pictures,
		    delay: 0
		 })( 'overlay' );
		
		checkIfRun();
		
		$('.main-content').click(function() {
			hasRun = true;
			checkIfRun();
			currentIndic();
		})
	
	
	
	
	
	
	
/////
		if (!Modernizr.touch){
			$(window).keyup(function(e){
				if(e.keyCode ==39){
					nextImg();
				}else if(e.keyCode == 37){
					prevImg();
				}
			})
		}
		
		
		
		
		
/////		
		$('.next').click(function() {
			nextImg()
		});
		
		$('.previous').click(function() {
			
			if( current > 0){
				prevImg();
			}
			
		});
		
		
		
		
/////		
		function nextImg(){

			if(hasRun == true){
				$.vegas('next');
				
				if(current < len-1){
					current++
					currentIndic();
				}else{
					current = 0
				}
					
			}else{
				hasRun = true;
				checkIfRun();
			}
	
			currentIndic();
			
			//Detects Current image only on next button
			if (current == pictures.length-1){
				$('.goto').delay(500).html(lookupSection().later).fadeIn(800);
				$('.arrow.next').click(function() {
					window.location.href ='/'+lookupSection().later+'/';
					
				});
				$(window).keyup(function(e){
					if(e.keyCode == 39){
					window.location.href = '/'+lookupSection().later+'/';
					}
				});
				
			}else if(current !== pictures.length-1){
				$('.goto').fadeOut();
			}
		}
		



/////		
		function prevImg(){
		
			if(hasRun == true){
				$.vegas('previous');
			}else{
				hasRun = true;
				checkIfRun();
			}
			
			if(current > 0){
				current--;
			}else{
				current = len-1
			}
			
			currentIndic();
			
			if(current !== pictures.length-1){ 
				$('.goto').fadeOut();
			}
	
		
		}
	}
	
/*-----------------------------------------------------------------------*/
/* ! Services Page */
/*----------------------------------------------------------------------*/
	
	if(!Modernizr.touch){
		$('.menu').hover(function() {
			if (hasHov == false){
				$(this).append('<span class="thumb-overlay"></span>');

				$($(this),'img').stop().fadeTo(200, 0.8);
			
				$('.thumb-overlay').fadeIn(200);
				
				hasHov = true;
			}
			
		},function() {
			
			if (hasHov == true) {			
				$($(this),'img').stop().fadeTo(200, 1);
				
				$('.thumb-overlay').fadeOut(200, function() {
					$(this).remove();
				})
				
				hasHov = false;
			}
			
		});
		
	}
	
	if (handheld == false){
		$('.menu').click(function() {
			
			var pdfSrc = $('a', this).attr('data-pdf-src');
			console.log(pdfSrc);
			
			$('body').append('<div class="menu-overlay"><div class="menu-close"></div><a class="menu-pdf" href="/admin/'+pdfSrc+'"></a><div class="menu-print"></div><img src="' + $('a',this).attr('href') + '" alt="MAI Menu" /></div>');
			
			$('.menu-overlay').fadeIn(500);
			
			
			
			
			goModal();
			
			return false;

		});
	}
	
	function goModal() {
		
		
		
		$('.menu-overlay').css({
		
			width: pageWdt,
			height: pageHgt
		
		});
		
		$('.menu-print').click(function() {
			
			window.print();

		})
		
		$('.menu-close').click(closeModal)
		
		$('body').css({
			
			"overflow" : "hidden"
		
		});
	};
	
	
	function closeModal() {
		
		$('.menu-overlay').fadeOut(500, function() {
			$(this).remove();
		});
		
		$('body').css({
			
			"overflow" : "auto"
		
		});
		
	}
	
		
	
	
/*-----------------------------------------------------------------------*/
/* ! Router & Shifter for Providers + Collection*/
/*----------------------------------------------------------------------*/

	
	$('.card').each(function(i){
		
		var that = $(this);
		
		toPass = inc.toString()+"px";
		that.css({"left" : document.documentElement.clientWidth*i+"px"});
		
		setTimeout(function(){
			that.removeClass('no-vis');
		},400);
		
		cards.push({el:that , pos:inc})
		
		if(i != current){
			that.hide();	
		}	
	});
	
	
	if(prov == true){
		$('.card').fadeOut(0);
		
		
		name.each(function(i) {
		
			pImgBg.push( $(this).attr('data-bg-src') );
			
			
		    providerNames.push( {nid : $(this).attr('data-nid') , path : pImgBg[i]} );
		});
		
		$.address.init( function(evt){
		
			if(	evt.value != '/' ){
				deepLink = true;
			}		
		
		}).change( function(evt){
			
			if( evt.value == '/' ){
				
				if( deepLink == false ){
					
					runx++;
						
					if(runx > 1){
						
						window.location.href = '/';
						
					}else{
						
						$.address.value( providerNames[0].nid );
						//cards[current].el.fadeIn(220);
						
					}
					
					
				
				}else{
					
					run++;
					
					if(run > 1){
						
						window.location.href = '/';
						
					}else{
					
						$.address.value( providerNames[0].nid );
						//cards[current].el.fadeIn(220);
					
					}
					
				}
								
			}else{
				

				
				//check if current card matches the url
				var		ii			=		0
				,		match		=		false
				,		templen		=		providerNames.length
				,		loc			=		evt.value.split('/',2)[1];
				
				
				$('.card').fadeOut(0); 
				
					
				for(ii; ii<templen; ++ii){
					
					if(	providerNames[ii].nid	==	loc ){
						
						current = ii;
						//cards[current].el.fadeIn(220);
						currentIndic();
						
						if(ii>0){
							
							$('.goback').fadeOut(20);
						
						}
						
					}
					
				}
			
				
				// Set initial Providers BG
				doProvidersBg();
				
			}
				
				
			
			
		});
		
		
	}
	
	
	//Init interactions
	if(!$('body').hasClass('home')){
		
		$('.arrow').click(function(evt){
			
			shiftAndSlide($(this).attr('data-dir'));	
			evt.preventDefault();
			
		});
		
		if (!Modernizr.touch){
			//Handle Keyboard Evts
				$(window).keyup(function(e){
					if(e.keyCode ==39){
						shiftAndSlide('next')
					}else if(e.keyCode == 37){
						shiftAndSlide('prev')
					}
				
				})
			}
	}
	
	// Shift & Slide funcs for Providers Page
	function shiftAndSlide(dir){
		
		
		$('.goback , .goto').fadeOut(20);

		
		if(dir == "next"){
					
				
			if(current < (cards.length-1)){
				$('.goto').fadeOut(220);
				
				cards[current].el.fadeOut(220, function() {
					current++;
					currentIndic();
					
					//Deep linking for providers
					if(prov == true){
						
						$.address.value( providerNames[current].nid );//.update();
						
						//Sep 8
						//doProvidersBg();
						
						
					
					}else{
					
						cards[current].el.fadeIn(220);
					
					}
					
					
				});	
				
				if(current == cards.length-2){
					$('.goto').html(lookupSection().later).delay(200).fadeIn(220)
				}
							
			}else{

				if($('body').hasClass('contact') ){
					window.location.href ='/';
				}else{
					window.location.href = '/'+lookupSection().later+'/';
				}
			}
			
						
		}else if(dir == "prev"){
			
			
			if($('body').hasClass('.home')){
				
				prevImg();
				
			}
			
			if(current > 0){
			
				cards[current].el.fadeOut(220, function() {					
					current--;
					currentIndic();
					//Deep linking for providers
					//if(lookupSection().now == 'providers'){
					if( prov == true ){	
						$.address.value( providerNames[current].nid );//.update();
						//Sep 8
						//doProvidersBg();
					
					}else{
						
						cards[current].el.fadeIn(220);
						
					}	

					

					
				});
				
				if(current == 1){
				
					$('.goback').html(lookupSection().then).delay(200).fadeIn(220);

				}
				
			}else{
				
				if($('body').hasClass('providers') ){
					window.location.href ='/';
				}else{
					window.location.href = '/'+lookupSection().then+'/';
				}
				
			}
			
			
		}
		
		
		
	}
	
	
	
	
	
	function shiftTo(pos,report){
	
		$('.goback , .goto').fadeOut(20);
		
		if ($('.home').length > 0){
			
			$.vegas('jump',pos);
			
			current = pos;
			//updateAddress( current );
			currentIndic();
			
		}else{
			
			cards[current].el.fadeOut(220, function() {
				
				current = pos;
				currentIndic();
				
				if(prov == true){
						
					//updateAddress( current );
					
					$.address.value( providerNames[current].nid );//.update();
					//pImg.attr('src','/style/placeholders/'+providerNames[current].path);
					
					//Sep 8
					//doProvidersBg();
					
					//cards[current].el.fadeIn(220);
					
				}else{
						
					cards[current].el.fadeIn(220);
						
				}
									
			});
			
		
		}
				
		
		
		if(pos == cards.length-1){
			$('.goto').html(lookupSection().later).delay(200).fadeIn(220)
		}
		
		if(pos == 0){
			$('.goback').html(lookupSection().then).delay(200).fadeIn(220)
		}
		
	}
	
	
	
/*-----------------------------------------------------------------------*/
/* ! Utilities */
/*----------------------------------------------------------------------*/
	
	//***** Resize Providers Img ***** //
	function imgResize(){
		//alert( $(window).height() +  ' / ' + window.innerHeight + ' / ' + document.height )
		
		/*
setTimeout(function(){
		
		$('.pro-name').append( $(window).height() + ' / ' + window.innerHeight )
		
		},2300)
*/
		
        var ww 		= 		$( window ).width()
        ,   wh 		= 		getTrueHeight()
        ,   iw 		= 		pImg.width()
        ,   ih 		= 		pImg.height()
        ,   rw 		= 		wh / ww
        ,   ri 		= 		ih / iw
        ,   newWidth 
        ,   newHeight
        ,   newLeft 
        ,   newTop
        ,   properties;
		
		
		
		
        if ( rw > ri ) {
            newWidth = wh / ri;
            newHeight = wh;
        } else {
            newWidth = ww;
            newHeight = ww * ri;
        }
	
		//setTimeout(function(){$('.pro-name').append( getTrueHeight()+'/'+tablet+'/'+document.height );},2000);
	
        properties = {
            'width': newWidth + 'px',
            'height': newHeight + 'px',
			'top': 'auto',
			'bottom': 'auto',
			'left': 'auto',
			'right': 'auto'			
        }
		
        pImg.css( properties );
      
    }
    
    function getTrueHeight(){
    	
    	var nh = $( window ).height();
    	
    	if(tablet == true){
    		
    		nh = document.height;
    		
    	}
    	
    	return nh;
    	
    }
    
	
	function lookupSection (){
	
		var triad = {
			
			"then"	:	"",
			"now"	:	"",
			"later"	:	""
			
		},
		basePos = 0;
		
		triad.now = window.location.pathname.split('/',3)[1];
		
		for(var i=0; i<sections.length; ++i){
		
			if(sections[i] == triad.now){
			
				basePos = i;
				
			}
			
		}
		
		if(basePos == 0){
		
			triad.then = sections[sections.length-1];		
			triad.later = sections[basePos+1];
			
		}else if(basePos == sections.length-1){
		
			triad.then = sections[basePos-1];
			triad.later = sections[0];
			
		}else{
		
			triad.then = sections[basePos-1];
			triad.later = sections[basePos+1];
			
		}
		
		
		return triad;
	
	}
	
	//Since this is a % based layout, this function will determine the pixel width of ".setup" 
	function getWidth(perc){
		
		winSize =  document.documentElement.clientWidth*perc;
		return winSize;

	}
	
	function trace(arg){

		console.log( arg )
		
	}

	
	
	
	
	function resizeMain() {
		
		var mastHgt = $('.masthead').height();
		
		padTestStr = $('.main-content').css('paddingTop').split('px',2);
		mainPad = padTestStr[0];
		
		
		$('.main-content').css({
		
			height: window.innerHeight-mastHgt-mainPad							
		})
		
	};
	
	
	function checkIfRun(){
		if(hasRun == false){
			
			$('body.home .arrow.previous').css({opacity:0.4});
			indic.hide();
			$.vegas('pause');
		
		}else{
		
			indic.delay(500).fadeIn(500);
			$('.arrow.previous').delay(500).fadeTo(500, 1);
			
			if( $('body').hasClass('home') ) {
			
				$( '.main-content' ).fadeOut(500);
				$('.tooltip').fadeOut(500, function() {
					$(this).remove();
				})
			
			}
			
		}
	}
	
	
	function currentIndic(){
		
		$('.indic li').each(function(i) {
		
			if (i == current){
			
				$(this).addClass('current');	
							
			}else{
			
				$(this).removeClass('current');
			
			}
				
		});
		
	}
	
	
	
	
	
	function doProvidersBg(arg){
		
		if( !hasBg ){
			
			$('<div class="bg-container"><img class="providers-bg" src="'+providerNames[current].path+'" /></div>').hide().prependTo('body').fadeIn(220);
				
			pImg = $('.providers-bg');
			
			pImg.imagesLoaded(function() {
				
				imgResize();
				cards[current].el.fadeIn(220);
				
				
			});
		
			hasBg = true;
		
		}else if ( hasBg ){
			
			//pImg.fadeOut(500);
				
			pImg.fadeOut(220, function(){
				pImg = $('.providers-bg');
			
				pImg.hide().attr('src',providerNames[current].path);
	
				pImg.imagesLoaded(function() {
					imgResize();
					pImg.fadeIn(220);
					cards[current].el.fadeIn(220);
				});
			});
			
			
	
			
		}

		if(!nopacity){
			
			$('.bg-container img').css({"opacity":"0.1"});	
		
		}

	}
	
	
	
	currentIndic();
	
	
	//$(window).resize(resizer);
	$(window).bind( redrawEvt , resizer );

		
		
	function resizer() {
						
		pageWdt = $( window ).width();
		pageHgt = $( window ).height();		
		
		//goModal();
		
		if( prov ){
			
			imgResize();
			//doProvidersBg(1);
		
		}else if( serv ){
			$('.menu-overlay').css({
			
				width: pageWdt,
				height: pageHgt
			
			})
		}
		
	}
	
/*-----------------------------------------------------------------------*/
/* ! IE BUMMERS */
/*----------------------------------------------------------------------*/



	if(!nopacity && $('body').hasClass('contact') || $('body').hasClass('contact')){
	
		$('.vegas-overlay').css({
			
			"background":"#f0f0f0",
			"opacity":0.9
			
		});
	
	}

}); // LA FIN
