var index_array = new Array(1, -1, 0);
//Exhibitions: 
//Novos flyers: juntar dimensao/comprimento/px a widthArray.
var widthArray = new Array(609, 414, 824, 812, 508, 508, 665);
var exhibition_count = widthArray.length;
var quoIndex = 2;
var isTabOpen = false;
var navBarLeft = 880;
//Work:
var img_count = 28;
var img_width = 890;
var b;
//home:
//home_animation: adicionar imagens ao slideshow atraves do home_count
var home_count = 6; 
var tt= null; var is_running = false; var home_index = 0; var I = new Image(); var path = "resources/images/home/00.jpg";

$(document).ready(function(){ 
    b = $.chekBrowser(); 
    //INIT:
	$("#webBy").show();
	//home:
	var im = new Image();
	im.onload = function () {
		$("#progress_bar").hide();
		$("#fundoImg").attr('src', im.src);
        $.home_animantion.run();
	};
	im.src = path;
    
	//HANDLERS:	
	//----------------------------------------- Stickers------------------------
	$("#sticker").hover(
	   function(){
		  $(this).attr('src', "resources/images/stickerValbom1.jpg");
	   }, function(){
		  $(this).attr('src', "resources/images/stickerValbom.jpg");
	   }
    );
	//--------------------------------------------------------------------------
	$("#fade_area, #mainContainer, #homeButton, #exhibitionButton, #workButton").click(function(){
	   if(isTabOpen){
            $.tab.close();
            $.home_animantion.run();
        }
    });
    $("#homeButton").click(function(){
	   $("#mainContainer").animate({
		  top: '0'
	   }, 1000, "easeInOutExpo");
	   $.home_animantion.run();
    });    
    $("#curriculumButton").click(function(e){
	   e.preventDefault();
	   $.tab.reset();
       $.home_animantion.stop();
	   $("#curriculum").delay(200).fadeIn(300);
	   if(!isTabOpen)$.tab.open();
    });
	$("#fundoImg").toggle(
		function(){$.home_animantion.stop()},
		function(){$.home_animantion.run()}
	);
    
    //texts:
    var text_array = [$("#text0"), $("#text1"), $("#text2"), $("#text3")];
    for (var i = 0; i < 4; i++){
        var me = text_array[i];
        me.click(function(e){
            var index= $(this).attr("data-index");
            e.preventDefault();
            $.tab.reset();
            $("#texts").html(textArray[index]).slideDown(400);
            $.home_animantion.stop();
            if(!isTabOpen)$.tab.open();
	   });
    }
    // Quotes:
    var quotes_count = quotationArray.length;
    $("#text4").click(function(e){
	   e.preventDefault();
	   $.tab.reset();
	   if (quoIndex > quotes_count - 1) quoIndex = 0;
	   var st = textArray[4] + '<h2><i>&laquo;' + quotationArray[quoIndex] + '&raquo;</i></h2><h4>Bernardo P. Almeida, <i> A desmedida voca&ccedil;&atilde;o da imagem,</i> 2010</h4>';
	   quoIndex +=1;
	   $("#texts").html(st).fadeIn(400);
       $("#email").fadeIn("slow");
       $.home_animantion.stop();
	   if(!isTabOpen)$.tab.open();
    }); 
    // menu buttons:
    $("#menu_buttons img").hover(
	   function(){
		  var ii = $(this).attr('data-index');
		  $(this).attr('src', pathArray1[ii]);
	   }, function(){
		  var ii = $(this).attr('data-index');
		  $(this).attr('src', pathArray[ii]);
	   }
    );
    $("#exhibitionButton").click(function(){
	   $("#mainContainer").animate({
		  top: '-700'
	   }, 1000, "easeInOutExpo");
	   $(".imgTop").css({opacity:0});
	   index_array[2] = 0;
	   $.select_flyer();
	   $.home_animantion.stop();
    });
    $("#workButton").click(function(){
	   $("#mainContainer").animate({
		  top: '-1400'
	   }, 1000, "easeInOutExpo");
	   index_array[0] = 1;
	   $.select_image();
	   $.home_animantion.stop();
    });    
    
    $("#webBy").hover(
	   function(){
		  $(this).animate({
			 width: 120
		  }, 400, "easeInOutExpo");
	   },
	   function(){
		  $(this).animate({
			 width: 30
		  }, 200, "easeInOutExpo");
	   }
    );
    // TABS:
    //navBar:
    $("#navBar").mouseover($.tool_tip.reset());
    //Exhibition:
    $("#prev").css({opacity:0}).hover(function(){
	    if(index_array[2] > 0)
			$(this).fadeTo(100,.5);
    }, function(){
        $(this).css({opacity:0});
    }).click(function(){
        if(index_array[2] == 1)
		    $(this).fadeTo(100,0);
		$.select_flyer.previous();
    });
    $("#next").css({opacity:0}).hover(function(){
        if(index_array[2] < exhibition_count - 1)
            $(this).fadeTo(100,.5);
    }, function(){
        $(this).css({opacity:0});
    }).click(function(){
	    if(index_array[2] == exhibition_count - 2)
		    $(this).fadeTo(100,0);
        $.select_flyer.next();
    });    
    $(".imgTop").css({opacity:0}).toggle(function(){
        var selected_ind = parseInt($(this).attr('data-index'));
        if (index_array[2] != selected_ind){
            index_array[2] = selected_ind;
            $.select_flyer();
        }
        $(this).css({opacity:1});
        $("#next").css({opacity:0});
        $("#prev").css({opacity:0});
    }, function(){
        $(this).css({opacity:0});
        $("#next").css({opacity:0});
        $("#prev").css({opacity:0});
    });
    $("#navBar").mouseover(function(){
        $("#next").css({opacity:0});
        $("#prev").css({opacity:0});
    });
    //Work:
    if (!b.mobile){
	   $("#work_img_container img").click(function(){
		  $.select_image.next();
	   }).mouseover(function(){
		  $.tool_tip.reset();
	   });
    }
    $("#controls img").click(function(){
	  index_array[0] = parseInt($(this).attr('data-index'));
	   $.select_image();
	   $.tool_tip.reset();
    }).hover(function(e){
		index_array[1] = parseInt($(this).attr('data-index'));
		$(this).attr('src','resources/images/square.png');
		//preview caption:
		var cap =  $("#work_img_container img")
	   .filter(function(index){
		  return $(this).attr("id") == index_array[1];
	   }).attr("data-caption");
		var ar = cap.split(", ", 1);
		if(index_array[1] != index_array[0]){
			var px = e.pageX - 90;
			$("#tool_tip").html(ar[0]).css({
				left: px
			}).delay(300).fadeIn('fast');
		}
	},function(){ 
		if($(this).attr("data-index") != index_array[0])
			$.tool_tip.reset();
	});
    //SWIPES:
    var speed = 300;
    var imgs;
    var swipeOptions = {
	   triggerOnTouchEnd : true,	
	   swipeStatus : swipeStatus,
	   threshold:90
    }
    $(function()
    {				
	   imgs = $("#work_img_container");
	   imgs.swipe( swipeOptions );
    });		
    
    //Catch each phase of the swipe. move : we drag the div. cancel : we animate back to where we were. end : we animate to the next image
    function swipeStatus(event, phase, direction, distance)
    {
	   if( phase=="move" && (direction=="left" || direction=="right") ) //If we are moving before swipe, and we are going Lor R in X mode, or U or D in Y mode then drag.
	   {
		  var duration = 0;
					
		  if (direction == "left")
			 scrollImages((img_width * index_array[0]) + distance, duration);
		  
		  else if (direction == "right")
			 scrollImages((img_width * index_array[0]) - distance, duration);
					
	   }
	   else if ( phase == "cancel")
	   {
		  scrollImages(img_width * index_array[0], speed);
	   }
	   else if ( phase =="end" )
	   {
		  if (direction == "right")
			 previousImage();
		  else if (direction == "left")			
			 nextImage();
	   }
    }
    function previousImage(){
	   index_array[0] = Math.max(index_array[0] - 1, 1);
	   imgs.stop(true, true);
	   scrollImages( img_width * index_array[0], speed);
	   //caption:
	   $.select_image.update_caption();
    }
    function nextImage(){
	   index_array[0] = Math.min(index_array[0] + 1, img_count);
	   imgs.stop(true, true);
	   scrollImages( img_width * index_array[0], speed);
	   //caption:
	   $.select_image.update_caption();
    }
		  
    function scrollImages(distance, duration) //Manually update the position of the imgs on drag
    {
	   distance -= (img_width + 22); // because indexes start at 1.
	   //imgs.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();
	   imgs.animate({left: value}, duration, "easeOutExpo");
    }
    // PRE-INIT:
    on_resize();
	$(window).resize(on_resize);
    //load images:
    var la = new Image();
    la.src = "resources/images/lawrence.jpg";
});

$.select_image= function(){
	var temp_easing = "easeInOutExpo";
	if (b.mobile){
	   temp_easing = "easeOutExpo";
    }
    var px =0;
    if(index_array[0] > img_count){
	    index_array[0] = img_count;
    }
    else if(index_array[0] < 1) {
	    index_array[0] = 1;
    }
    else{
	    px = ((index_array[0] - 1) * img_width) -2;
	    $("#work_img_container").animate({left:20 - px}, 1000, temp_easing);
	    //position & retrieve caption:
	    $.select_image.update_caption();
	}
}
$.select_image.update_caption = function(){
    //position caption:
    var target = $("#work_img_container img").filter(function(index){
	   return $(this).attr("id") == index_array[0];
    });
    var cpx = target.height();
    if(cpx < 580){
	   var f = (580 - cpx) / 2;
	   cpx += f;
    }
    cpx += 60;
    //retrieve caption:
    var caption =  target.attr("data-caption");
    $("#caption").hide().html(caption).delay(600).css('top',cpx).show(300);    
    //update controls:
    $("#controls img").attr('src','resources/images/squareGray.png')
	   .filter(function(i){
		  return $(this).attr("data-index") == index_array[0];
    }).attr('src','resources/images/square.png');
}
$.select_image.next = function(){ 
    index_array[0] += 1;
    $.select_image();
}
$.select_image.previous = function(){  
    index_array[0] -= 1;
    $.select_image();
}
$.tool_tip = function(){}
$.tool_tip.reset = function(){
	$("#tool_tip").hide();
	if (index_array[1] != index_array[0]){
		$("#controls img").filter(function(index){
				return $(this).attr('data-index') == index_array[1];
			}).attr('src','resources/images/squareGray.png');
	}
}
$.select_flyer = function(){
	var temp_easing = "easeInOutExpo";
	if (b.mobile) temp_easing = "easeOutExpo";
    var px =0; 
    if(index_array[2] < 0){
	    index_array[2] = 0;
	    if(b.mobile){
			 $("#exhibition").animate({left:100}, 400, temp_easing, function(){
			    $(this).animate({left:0}, 1000, temp_easing);
		    });
	    }
    } else if (index_array[2] > exhibition_count - 1){
	    index_array[2] = exhibition_count - 1;
	    if(b.mobile){
		    for (var i=0; i < index_array[2]; i++){
				  px += widthArray[i];
		    }
		    $("#exhibition").animate({left: - px - 150}, 400, temp_easing, function(){
			    $(this).animate({left: - px}, 1000, temp_easing);
		    });
	    }
    }else{
	    for (i = 0; i < index_array[2]; i++){
			   px += widthArray[i];
	    }
	    $("#exhibition").animate({
	    left: - px
	    }, 1000, temp_easing);
	}
}   
$.select_flyer.previous = function(){
    index_array[2] -=1;
    $.select_flyer();
}
$.select_flyer.next = function(){
    index_array[2] +=1;
    $.select_flyer();
}


$.tab = function(){}
$.tab.open = function(){
    var px = $(window).width() - 840;
    $.tab.animate(false, px);
}
$.tab.close = function(){
    $("#mainContainer").fadeTo(1000,1);
    $.tab.animate(true, navBarLeft);
}
$.tab.animate = function(is_closing, left){
     $("#navBar").animate({
		  left: left
	   },1000,"easeOutBack");
    if(is_closing){
        $.tab.reset();
        $("#fade_area").fadeOut(300);
        $("#shadow").fadeOut(300);
    }else{
        $("#shadow").fadeTo(300,.4);
        $("#fade_area").fadeIn(300);
    }
    isTabOpen = !is_closing;
}
$.tab.reset = function(){
    $("#curriculum").fadeOut(400);
    $("#texts").fadeOut(400);
    $("#email").hide();
}


$.home_animantion = function(){}
$.home_animantion.run = function(){
    
    if(!is_running){
        is_running = true;
        $.home_animantion.update();
    }
}
$.home_animantion.update = function(){
	
	$("#fundoImg").fadeOut("slow", function(){
		var im = document.getElementById("fundoImg");
		im.onload = new function(){
			$("#fundoImg").fadeIn("1000");
		};
		im.src = path;
		home_index +=1;
		if (home_index == home_count) home_index = 0;
		path = "resources/images/home/0" + home_index + ".jpg"
		I.src = path;
		tt = self.setTimeout("$.home_animantion.update()", 5000);
	});
}
$.home_animantion.stop = function(){
	//if(is_running);
    clearTimeout(tt);
    is_running = false;
}
	
function on_resize(){
	var pw = $(window).width();
	var ph = $(window).height();
	if(pw < 1070){
		$("#work").width(pw - 190);
		navBarLeft = pw - 190;
		if(!isTabOpen)
			$("#navBar").css({left: navBarLeft});
		$("#exhibitions").css({width: navBarLeft - 10});
	}else{
		$("#work").width(880);
		navBarLeft = 880;
		if(!isTabOpen)
			$("#navBar").css({left: navBarLeft});
		$("#exhibitions").css({width: navBarLeft - 10});	
	}
    if(ph < 650)
	   $("#navBar").css({top: -20});
    else
	   $("#navBar").css({top: 6});
}
$.chekBrowser = function (){
    var b = Array();
    var nua = navigator.userAgent;
    if (nua.indexOf("iPad")!=-1)b.ipad = true; else b.ipad=false;
    if (nua.indexOf("Safari")!=-1)b.safari=true;else b.safari = false;
    if (nua.indexOf("Chrome")!=-1)b.chrome=true;else b.chrome = false;
    if (nua.indexOf("Firefox")!=-1)b.firefox=true;else b.firefox=false;
    if (nua.indexOf("Mobile")!=-1)b.mobile=true;else b.mobile=false;
    if (nua.indexOf("MSIE")!=-1)b.ie=true;else b.ie=false;
    return b;
}
