var Site = window.Site || {};
var offsetArr = [];
var activeImg = 0;
var totalImg = 0;
var xOffset = 0;
var totalWidthOffset = 0;
var IMG_WIDTH = 0;

var duration = 300;
var speed = 400;
var minimumDrag = 40;
var width = 0;

var isMobile = false;
var isiOs = false;
var isiPad = false;


var isResizing = false;


/* Create a closure to maintain scope of the '$'
   and remain compatible with other frameworks.  */
(function($) {
	
	//same as $(document).ready();
	$(function() {
		
		
		// check if mobile
		if( navigator.userAgent.match(/Android/i) ||
 		navigator.userAgent.match(/webOS/i) ||
 		navigator.userAgent.match(/iPhone/i) || 
 		navigator.userAgent.match(/iPod/i)){
 			isMobile = true;
		}
		else
		{
		    isMobile = false;
		}
		
		// check if iOS
		if(navigator.userAgent.match(/iPhone/i) ||
		navigator.userAgent.match(/iPad/i))
 		{
 		    isiOs = true;
 		    if(navigator.userAgent.match(/iPad/i))
 		    {
 		    	isiPad = true;
 		    }
 		    else
 		    {
 		    	isiPad = false;
 		    }
 		}
 		
 		
 		if(isiPad)
 		{
 			document.addEventListener('touchmove', function(e)  { e.preventDefault(); }, false);
 		}

		
		// load the appropriate slides
		getRightSlides();
		
		
		// remove context menu -- theft prevention
		$("#slideshow").bind("contextmenu",function(e){
              return false;
       }); 
		
	});

	$(window).bind("load", function() {
	
	});
	
})(jQuery);


//*****************   ADAPTIVE IMAGES  ******************* //

function getRightSlides() {
	if(isMobile && !isiPad)   // if mobile and not ipad, get small images
	{
		$(".slides_container").load("slides-mobile.html", onImagesLoaded);
	}
	else if(isiPad)
	{
		$(".slides_container").load("slides-ipad.html", onImagesLoaded);
	}
	else  // else get the big ones
	{
		$(".slides_container").load("slides-big.html", onImagesLoaded);
	}
}

function onImagesLoaded() {

	$(".slides_container").waitForImages(function() {
	
		initContent();
		initSlideshow();
		
	});
}

// ---------------------- SLIDESHOW -------------------

function initSlideshow() {
		
		$("#slideshow").css('background-image', 'none');
		
		$(".slides_container").fadeIn("slow", function() {
			calculatePositions();
		});
		
		// get all image widths and coordis.
		$.each($(".slides_container img"), function(index) {
			offsetArr.push($(".slides_container img").eq(index).width());
			totalWidthOffset += $(".slides_container img").eq(index).width();
			totalImg++;
		});

		
		$(".slides_container").css('width', totalWidthOffset+'px');
		$("#slideshow").css('height', ($(".slides_container img").width()/1.6)+"px");
		
		updateIndicator();
		
		
		// ------------------  SLIDESHOW EVENTS  ----------------------
		
		// on stage resize
		$(window).resize(onStageResize);
		
		if(!isiOs) {// mouse events on browser
			$(".next").click(scrollNext);
			$(".prev").click(scrollPrev);
		}
		else { // mouse events on iOS
			$(".next").click(cssNextImage);
			$(".prev").click(cssPreviousImage);
		}		
		
		// keyboard events
		if(!isMobile)
		{
			$(window).keydown(function(key) {
			if(key.keyCode == 37) { 		// left
				scrollPrev();
			}
			else if(key.keyCode == 39) { 	// right
				scrollNext();
			}
			});

		}		
		
		// ----------------- SWIPE GESTURES ------------------
		
		var scrollArea = $(".slides_container");
		width = $(".slides_container img").eq(0).width();
		
		if(!isiOs) // in browser
		{
			$(".slides_container").draggable({axis: "x",
                    start: function(event) {
                      
                        var data = event.originalEvent.touches ? event.originalEvent.touches[0] : event;
                        start = {
                            coords: [ data.pageX, data.pageY ]
                        };

                    },
                    stop: function(event) {
                       
                        var data = event.originalEvent.touches ? event.originalEvent.touches[0] : event;
                        stop = {
                            coords: [ data.pageX, data.pageY ]
                        };

                        start.coords[0] > stop.coords[0] ? moveLeft() : moveRight();

                        function moveLeft() {
                           activeImg++;
                           if (activeImg >= totalImg) {
                               	activeImg = totalImg-1;
                                scrollArea.animate({ left: (-totalWidthOffset+offsetArr[activeImg])+"px"}, duration);
                                updateIndicator();
                                return;
                            }
                            else if(dragDelta() < minimumDrag)
                            {
                            	activeImg--;
                            	//xOffset = -offsetArr[activeImg];
                            	scrollArea.animate({ left: xOffset+"px"}, duration);
                            	updateIndicator();
                                return;
                            }
                            else
                            {
                            	xOffset -= offsetArr[activeImg];
                            	scrollArea.animate({ left: xOffset+"px"}, duration);
                            	updateIndicator();	
                            }
                        }

                        function moveRight() {
                           activeImg--;
                           if (activeImg < 0) {
                                scrollArea.animate({ left: 0+"px"}, duration);
                                activeImg = 0;
                                xOffset = 0;
                                updateIndicator();
                                return;
                            }
                            else if(dragDelta() < minimumDrag)
                            {
                            	activeImg++;
                            	//xOffset = -offsetArr[activeImg];
                            	scrollArea.animate({ left: xOffset+"px"}, duration);
                            	updateIndicator();
                                return;
                            }
                            
                            xOffset += offsetArr[activeImg];
                            scrollArea.animate({ left: xOffset + "px"}, duration);
                            updateIndicator();
                        }

                        function dragDelta() {
                            return Math.abs(start.coords[0] - stop.coords[0]);
                        }

                        function adjustment() {
                            return width - dragDelta();
                        }
                    }
         	});
		}
		
		else {   // on iOS devices
			
			IMG_WIDTH = $(".slides_container img").eq(0).width();
			
			//$(".slides_container").css('-webkit-transform', 'translate3d(0px,0px,0px)');
			//$(".slides_container img").css('-webkit-transform', 'translate3d(0px,0px,0px)');
			
			var swipeOptions=
			{
				triggerOnTouchEnd : true,	
				swipeStatus : swipeStatus,
				allowPageScroll:"vertical",
				click: hideAllContent,
				threshold:80
			}
			
			$(".slides_container img").swipe( swipeOptions );
		}
		
                
}

//------------ iOS - CSS ANIMATIONS  -------------- //

function swipeStatus(event, phase, direction, distance)
{
    //If we are moving before swipe, and we are going L or R in X mode, or U or D in Y mode then drag.
    if( phase=="move" && (direction=="left" || direction=="right") )
    {
    	var duration=0;
    	
    	if (direction == "left")
    		cssScrollImages((IMG_WIDTH * activeImg) + distance, speed);
    	
    	else if (direction == "right")
    		cssScrollImages((IMG_WIDTH * activeImg) - distance, speed);
    	
    }
    
    else if ( phase == "cancel")
    {
    	cssScrollImages(IMG_WIDTH * activeImg, speed);
    }
    
    else if ( phase =="end" )
    {
    	if (direction == "right")
    		cssPreviousImage()
    	else if (direction == "left")			
    		cssNextImage()
    }
}


function cssScrollImages(distance, duration)
{
    $(".slides_container").css("-webkit-transition-duration", (duration/1000).toFixed(1) + "s");
    
    //inverse the number we set in the css
    var value = (distance<0 ? "" : "-") + Math.abs(distance).toString();
    
    $(".slides_container").css("-webkit-transform", "translate3d("+value +"px,0px,0px)");
    
    updateIndicator();
}

function cssPreviousImage()
{
     activeImg = Math.max(activeImg-1, 0);
    cssScrollImages( IMG_WIDTH * activeImg, speed);
    return false;
}

function cssNextImage()
{
    activeImg = Math.min(activeImg+1, totalImg-1);
    cssScrollImages( IMG_WIDTH * activeImg, speed);
    return false;
}

// -------------------------------------------------- //



function scrollNext() {
		activeImg++;
		if(activeImg >= totalImg) {
		    activeImg = 0;
		    xOffset = 0;
		    $(".slides_container").animate({left: xOffset+"px"}, 1200);
		    updateIndicator();
		}
		else
		{
		    xOffset -= offsetArr[activeImg];
		    $(".slides_container").animate({left: xOffset+"px"}, speed);
		    updateIndicator();
		}
		
		return false;
}

function scrollPrev() {
		activeImg--;
		if(activeImg < 0) {
		    activeImg = totalImg-1;
		    xOffset = -totalWidthOffset+offsetArr[activeImg];
		    $(".slides_container").animate({left: xOffset+"px"}, 1200);
		    updateIndicator();
		}
		else
		{
		    $("#slideshow img").eq(activeImg).show();
		    xOffset += offsetArr[activeImg];
		    $(".slides_container").animate({left: xOffset+"px"}, speed);
		    updateIndicator();
		}
		
		return false;
}

function updateIndicator() {
	$("#indicator").text("( "+ (parseInt(activeImg)+1) + " / " + totalImg+" ) ");
}



// --------------------  CONTENT  ------------------------------


function initContent() {
	
	$("#photo-item a").click(function() {
		hideAllContent();
		removeActiveState();
		$("#photo-item").addClass("active");
		return false;
	});
	$("#bio-item a").click(toggleBio);
	$("#contact-item a").click(toggleContact);
	
	$("#bio .close-btn").click(toggleBio);
	$("#contact .close-btn").click(toggleContact);
	
	// center content in height
	if(!isMobile && !isiPad)
	{
		var newYContent = (($(window).height() - $("section").outerHeight() - 90) / 2) - 10;
		$("section").css("top", newYContent);	
	}	
	
	// remove telephone links unless it's a mobile device
	$(".phone a ").click(function() {
		if(!isMobile) return false;
	});	
	
	
	// fix bio content for mobile
	
	if(isMobile)
	{
		$("#slideshow").before($("#bio"));
		$("#bio").hide();
	}
	
	// write email address - spam protector
	$("#contact .email").html("<a href='mailto:&#115;&#116;&#117;&#100;&#105;&#111;&#064;&#109;&#105;&#107;&#101;&#118;&#097;&#110;&#099;&#108;&#101;&#118;&#101;&#110;&#046;&#099;&#111;&#109;'>&#115;&#116;&#117;&#100;&#105;&#111;&#064;&#109;&#105;&#107;&#101;&#118;&#097;&#110;&#099;&#108;&#101;&#118;&#101;&#110;&#046;&#099;&#111;&#109;</a>");	
}

function hideAllContent() {
		
	if(bioOn)
	{
		toggleBio();
	}
	if(contactOn)
	{
		toggleContact();
	}
	
	return false;
}

function removeActiveState() {
	
	$("#photo-item").removeClass('active');
	$("#bio-item").removeClass('active');
	$("#contact-item").removeClass('active');
}

function toggleBio() {
	
	if(contactOn) toggleContact();
	removeActiveState();
	
	if(!isMobile) { // if not mobile device

		if(bioOn) // close
		{
			$("#bio").animate({
					top: bioInY+'px'
				}, 300, function() {
					bioOn = !bioOn;
				});
				
				$("#photo-item").addClass("active");
			
		}
		
		else // open
		{
			$("#bio").animate({
			    	top: bioOutY+'px'
				}, 300, function() {
			    	bioOn = !bioOn;
				});
				
				$("#bio-item").addClass("active");
		}
	}
	
	else { // if mobile device
		if(bioOn)
		{
			$("#bio").hide();
			$("#photo-item").addClass("active");
		}
		else
		{
			$("#bio").show();
			$("#bio-item").addClass("active");
		}
		
		bioOn = !bioOn;
	}
	
	return false;
}

function toggleContact() {
	
	if(bioOn) toggleBio();
	removeActiveState();
	
	if(contactOn) // close
	{
		$("#contact").animate({
				top: contactInY+'px'
			}, 300, function() {
				contactOn = !contactOn;
			});
			
			
		$("#photo-item").addClass("active");
	}
	
	else // open
	{
		$("#contact").animate({
		    	top: contactOutY+'px'
			}, 300, function() {
		    	contactOn = !contactOn;
			});
			
			$("#contact-item").addClass("active");
	}
	
	return false;
}

var bioOn = false;
var bioOutY;
var bioInY;
var bioHeight;

var contactOn = false;
var contactOutY;
var contactInY;
var contactHeight;

function calculatePositions() {
	
	if($("#slideshow img").eq(0).height() <= 0)
	{
		$("#slideshow").height($(window).width() / 1.6);
	}
	else
	{
		$("#slideshow").height($("#slideshow img").eq(0).height());	
	}
	
	bioHeight = $("#bio").outerHeight();
	bioOutY = $("#slideshow").height() - bioHeight;
	bioInY = $("#slideshow").height();
	
	contactHeight = $("#contact").outerHeight();
	contactInY = bioInY;
	contactOutY = $("#slideshow").height() - contactHeight;
	
	if(!isMobile)
	{
		if(bioOn)
		{
			$("#bio").css('top', bioOutY);
		}
		else
		{
			$("#bio").css('top', bioInY);
		}
	}
	else
	{
		$("#bio").css('top', 0);
	}
	
	if(contactOn)
	{
		$("#contact").css('top', bioOutY);
	}
	else
	{
		$("#contact").css('top', bioInY);
	}
}


// --------------------  ON STAGE RESIZE  ------------------------------


function onStageResize() {
	if(!isResizing)
	{		
		isResizing = true;
		offsetArr = [];
		totalWidthOffset = 0;
		xOffset = 0;
		totalImg = 0;
		activeImg = 0;
		if(isiOs)
		{
			IMG_WIDTH = $(".slides_container img").eq(0).width();
			$(".slides_container").css('-webkit-transform', 'translate3d(0px,0px,0px)');
		}
		
		$.each($(".slides_container img"), function(index) {
		    offsetArr.push($(".slides_container img").eq(index).width());
		    totalWidthOffset += $(".slides_container img").eq(index).width();
		    totalImg++;
		});
		
		$(".slides_container").css('width', totalWidthOffset+'px');
		$("#slideshow").css('height', ($(".slides_container img").eq(0).width()/1.6)+"px");
		$(".slides_container").css("left", 0);
		width = $(".slides_container img").eq(0).width();
		
		// center content in height
		if(!isMobile && !isiPad)
		{
			var newYContent = (($(window).height() - $("section").outerHeight() - 90) / 2) - 10;
			$("section").css("top", newYContent);	
		}
		
		updateIndicator();
		calculatePositions();
		isResizing = false;
	}
}


function floatAndTrim(toTrim)
{
	return parseFloat(toTrim.substr(0, toTrim.length - 2));
}
