/* JS Title */

var bDescription	= false;
var bFixed			= false;
var carouselShowcaseCallback = null;

var carouselShowcase = {  

  setup: function(selectors, itemsPerSlide, wrapType) {

    $(selectors).each(function(){
      var navHtml = '<a href="#" class="prev"></a><a href="#" class="next"></a>',
          pages = Math.ceil($(this).find('ul li').size() / itemsPerSlide);

      if (pages == 1) return;

      for(i = 1; i <= pages ; i++) {
		navHtml = navHtml + '<a href="#" class="page" data-page="' + i + '"><div>' + i + '</div></a>';
      } 
	  
      // append extra markup
      //$(this).append('<div class="nav"><div class="nav-content"><div class="nav-text"><dl><dt><span id="showcase-item-title"></span></dt><dd><span id="showcase-item-description"></span></dd></dl></div><div class="nav-pages">' + navHtml + '</div></div></div>')
	  $(this).append('<div class="nav"><div class="nav-content"><div class="nav-text title-nav"><span id="showcase-item-title"></span></div><div class="nav-pages">' + navHtml + '</div></div></div>')
             .addClass('carousel-showcase-enabled')
             .data('items', itemsPerSlide)
			 .data('wrap', wrapType);

      // setup carousel
      $(this).find('ul').jcarousel({
	  	/*visible: 0,*/
		/*size					: 10,*/
	    vertical				: false,
		animation				: 500,
	    auto					: 5,
		itemFallbackDimension 	: 996,
	    /*itemFallbackDimension 	: docWidth,*/
        scroll                	: itemsPerSlide,
        initCallback          	: carouselShowcase.init,
        itemFirstInCallback   	: {
          onBeforeAnimation   	: function(carousel, state) { $('.carousel-showcase-enabled .nav-text').fadeOut(); },
          onAfterAnimation    	: function(carousel, state) { carouselShowcase.setText(carousel, state); $('.carousel-showcase-enabled .nav-text').fadeIn(); carouselShowcase.setNavActive(carousel, state); }
        },
        /*buttonNextHTML       	: null,*/
        /*buttonPrevHTML       	: null,*/
		wrap				  	: wrapType
      });

    });
  },

  init: function(carousel) {
    var el = carousel.container.parents('.carousel-showcase-enabled');

    el.find('.next').click(function(e){
      e.preventDefault();
      carousel.next();
    });

    el.find('.prev').click(function(e){
      e.preventDefault();
      carousel.prev();
    });

    el.find('.page').click(function(e){
      e.preventDefault();
      var page = $(this).data('page');
	  //var page = $(this).attr('href');
      carousel.scroll((page - 1) * el.data('items') + 1);
    });
	
	//Stop on Rollover and Start 30 seconds after Rollout
	
	carouselShowcaseCallback = setTimeout(function() {
		carousel.startAuto();
	}, 30000);
	
	carousel.clip.hover(function() {
        carousel.stopAuto();
        clearTimeout(thumbAnimCallback);
    }, carouselShowcaseCallback);
	
	//Hide Buttons on Startup
	
	$(".jcarousel-skin .jcarousel-next-horizontal, .jcarousel-skin .jcarousel-prev-horizontal").hide();
	
	//Set Fixed Title (or inital)
	
	var sFixedTitle = $('#carousel-showcase').data('title');
			
	if(sFixedTitle != undefined)
	{
		$('#showcase-item-title').html(sFixedTitle);
		$(".carousel-showcase-enabled .nav").slideDown("fast");
		//$('#showcase-item-description').html(sDescription);
		bFixedDescription = true;
	}

  },

  setNavActive: function(carousel, state) {
    var el      = carousel.container.parents('.carousel-showcase-enabled'),
		wrap	= el.data('wrap'),
        itemsPerSlide = el.data('items'),
        page    = Math.ceil((carousel.first - 1 ) / itemsPerSlide + 1),
        count   = Math.ceil(el.find('ul li').size() / itemsPerSlide);

    // update page status
    el.find('.active').removeClass('active');
    el.find('.page[data-page=' + page + ']').addClass('active');

    // update page nav 
    el.find('.prev-disabled').removeClass('prev-disabled');
	el.find('.next-disabled').removeClass('next-disabled');

    if (page == 1 && wrap != 'first' && wrap != 'both' && wrap != 'circular') {
		el.find('.prev').addClass('prev-disabled');
	} else if (page == count && wrap != 'last' && wrap != 'both' && wrap != 'circular') {
		el.find('.next').addClass('next-disabled');
    }

  },
  
  setText: function(carousel, state) {
  	$('#carousel-showcase  .carousel-showcase-div-item').each(function(index) {
		if(index == carousel.first-1)
		{
			var sTitle = $(this).data('title');
			var sDescription = $(this).data('description');
			
			if((sTitle != undefined) && (sDescription != undefined))
			{
				$('#showcase-item-title').html(sTitle);
				$(".carousel-showcase-enabled .nav").slideDown("fast");
				//$('#showcase-item-description').html(sDescription);
				bDescription = true;
			}
		}
	});
  },
  
  showNav: function () {
	if(bDescription)
	{
		$(".carousel-showcase-enabled .nav").slideDown("fast");
	}
	$(".jcarousel-skin .jcarousel-next-horizontal, .jcarousel-skin .jcarousel-prev-horizontal").fadeIn("fast");
  },
	
  hideNav: function () {
  	//$(".carousel-showcase-enabled .nav").slideUp("fast");
	$(".jcarousel-skin .jcarousel-next-horizontal, .jcarousel-skin .jcarousel-prev-horizontal").fadeOut("fast");
  }
  
};

var carouselInnovation = {
	
  setup: function(selectors, itemsPerSlide, wrapType) {

    $(selectors).each(function(){
      var navHtml = '<a href="#" class="prev"></a><a href="#" class="next"></a>',
          pages = Math.ceil($(this).find('ul li').size() / itemsPerSlide);

      if (pages == 1) return;

      for(i = 1; i <= pages ; i++) {
        //navHtml = navHtml + '<a href="#" class="page" data-page="' + i + '">' + i + '</a>';
		//navHtml = navHtml + '<a href="' + i + '" class="page" data-page="' + i + '">' + i + '</a>';
		//navHtml = navHtml + '<a href="' + i + '" class="page" data-page="' + i + '"><div></div></a>';
		navHtml = navHtml + '<a href="#" class="page" data-page="' + i + '"><div>' + i + '</div></a>';
      }
	  
      // append extra markup
      $(this).append('<div class="nav"><div class="nav-content"><div class="nav-text title-nav"><span id="innovation-item-title">Innovation</span></div><div class="nav-pages">' + navHtml + '</div></div></div>')
             .addClass('carousel-innovation-enabled')
             .data('items', itemsPerSlide)
			 .data('wrap', wrapType);

      // setup carousel
      $(this).find('ul').jcarousel({
	  	/*visible: 0,*/
		/*size					: 10,*/
	    vertical				: false,
		animation				: 500,
	    /*auto					: 5,*/
	    itemFallbackDimension 	: 996,
        scroll                	: itemsPerSlide,
        initCallback          	: carouselInnovation.init,
        itemFirstInCallback   	: {
          /*onBeforeAnimation   	: function(carousel, state) { $('.carousel-innovation-enabled .nav-text').fadeOut(); },
          onAfterAnimation    	: function(carousel, state) { carouselInnovation.setText(carousel, state); $('.carousel-innovation-enabled .nav-text').fadeIn(); carouselInnovation.setNavActive(carousel, state); }*/
		  onBeforeAnimation   	: function(carousel, state) {  },
          onAfterAnimation    	: function(carousel, state) { carouselInnovation.setNavActive(carousel, state); }
        },
        buttonNextHTML       	: null,
        buttonPrevHTML       	: null,
		wrap				  	: wrapType
      });

    });
  },

  init: function(carousel) {
    var el = carousel.container.parents('.carousel-innovation-enabled');

    el.find('.next').click(function(e){
      e.preventDefault();
      carousel.next();
    });

    el.find('.prev').click(function(e){
      e.preventDefault();
      carousel.prev();
    });

    el.find('.page').click(function(e){
      e.preventDefault();
      var page = $(this).data('page');
	  //var page = $(this).attr('href');
      carousel.scroll((page - 1) * el.data('items') + 1);
    });
	
	//Hide Buttons on Startup
	
	$(".jcarousel-innovation-skin .jcarousel-next-horizontal, .jcarousel-innovation-skin .jcarousel-prev-horizontal").hide();

  },

  setNavActive: function(carousel, state) {
    var el      = carousel.container.parents('.carousel-innovation-enabled'),
		wrap	= el.data('wrap'),
        itemsPerSlide = el.data('items'),
        page    = Math.ceil((carousel.first - 1 ) / itemsPerSlide + 1),
        count   = Math.ceil(el.find('ul li').size() / itemsPerSlide);

    // update page status
    el.find('.active').removeClass('active');
    el.find('.page[data-page=' + page + ']').addClass('active');

    // update page nav 
    el.find('.prev-disabled').removeClass('prev-disabled');
	el.find('.next-disabled').removeClass('next-disabled');

    if (page == 1 && wrap != 'first' && wrap != 'both' && wrap != 'circular') {
		el.find('.prev').addClass('prev-disabled');
	} else if (page == count && wrap != 'last' && wrap != 'both' && wrap != 'circular') {
		el.find('.next').addClass('next-disabled');
    }

  },
  
  /*
  setText: function(carousel, state) {
  	$('#carousel-innovation .carousel-innovation-div-item').each(function(index) {
		if(index == carousel.first-1)
		{
			$('#innovation-item-title').html($(this).data('title')); 
			//$('#innovation-item-description').html($(this).data('description'));
		}
	});
  },
  */
  
  slideDown: function () {
  	//$("#innovation .mask1, #innovation .mask2, #innovation .mask3, #innovation .mask4").css("top", "240px");
  	$("#innovation .mask1").css("display", "block");
  	$("#innovation .mask2").css("display", "block");
  	$("#innovation .mask3").css("display", "block");
  	$("#innovation .mask4").css("display", "block");
  	$("#innovation").animate({height:"306px"},"fast");
	setTimeout(function(){ $("#innovation .mask1").animate({ top: "306px" }, "fast") }, 200);
	setTimeout(function(){ $("#innovation .mask2").animate({ top: "306px" }, "fast") }, 300);
	setTimeout(function(){ $("#innovation .mask3").animate({ top: "306px" }, "fast") }, 400);
	setTimeout(function(){ $("#innovation .mask4").animate({ top: "306px" }, "fast") }, 500);
  },
	
  slideUp: function () {
  	$("#innovation").animate({height:"240px"},"fast", function () { $("#innovation .mask1, #innovation .mask2, #innovation .mask3, #innovation .mask4").css("top", "240px") });
  }
	
};

var currentImage = 1;

var imageSwap = {
	
	next: function (total) {
		
		if(currentImage < total) {
			currentImage++;
		}
		else {
			currentImage = 2;
		}
		
		imageSwap.fade($("#img_" + currentImage).data('selector'));
	},
	
	prev: function (total) {
		
		if(currentImage > 2) {
			currentImage--;
		}
		else {
			currentImage = total;
		}
		
		imageSwap.fade($("#img_" + currentImage).data('selector'));
	},
	
	fade: function (source) {
		
		//Swap Attributes
		
		var mainThumb = $("#imageMain").data("thumb");
		var mainImage = $("#imageMain").data("image");
		
		var thisThumb = $(source).data("thumb");
		var thisImage = $(source).data("image");
		
		//Fade Swap
		
		$("#imageMain").ImageSwitch({NewImage:thisImage, Speed: 300});
		$(source).ImageSwitch({NewImage:mainThumb, Speed: 300});
		
		//Update Attributes
		
		$("#imageMain").data("thumb", thisThumb);
		$("#imageMain").data("image", thisImage);
		$(source).data("thumb", mainThumb);
		$(source).data("image", mainImage);
	}
	
};

var divSwap = {
	
	scroll: function (source) {
		
		var link		= $(source).offset().top;	//variable
		var container	= $("#list").offset().top;	//fixed
		
		if(link != container)
		{
			if(container < link)
			{
				var position = link-container;
				$('#list-scroll').animate({top: "-="+position+"px"},'fast');
			}
			else
			{
				var position = container-link;
				$('#list-scroll').animate({top: "+="+position+"px"},'fast');
			}
		}
	},
	
	displayInfo: function (source) {
		
		if($(source + " .info").css('display') == "none")
		{
			$(source + " .button").css('background-position', '73px -13px');
			//$(source + " .info").show('fast');
			$(source + " .info").animate({ height: "show" }, 'fast');
			//$(source).css({ backgroundColor: '#fafafa'}, "fast");
		}
		else
		{
			$(source + " .button").css('background-position', '73px 0');
			//$(source + " .info").hide('fast');
			$(source + " .info").animate({ height: "hide" }, 'fast');
			//$(source).css({ backgroundColor: '#ffffff'}, "fast");
		}
	}
	
};

var thumbAnimCallback = null;
var thumbAnimCount;

var thumbAnim = {

	movePage: function (selector, thumbPage, pages) {
		
		if(thumbPage < pages-1)
		{
			thumbPage++;
			thumbAnimCount = thumbPage;
			
			thumbAnimCallback = setTimeout(function(){
				thumbAnim.movePage(selector, thumbPage, pages);
			}, 800);
			
			$(".c4thumb", selector).animate({
				backgroundPosition: '-' + (thumbPage*226) + 'px'
			}, 'fast', 'linear', thumbAnimCallback);
		}
	},
	
	start: function() {
		
		if($(".c4thumb", this).data("width")%226 == 0)
		{
			thumbAnim.movePage(this, 0, $(".c4thumb", this).data("width")/226)
		}
	},
	
	stop: function() {
		
		$(".c4thumb", this).stop();
		
		clearTimeout(thumbAnimCallback);
		
		$(".c4thumb", this).animate({
			backgroundPosition: 0
		}, thumbAnimCount*100, 'linear');
	}
	
};

var map;

var contactMap = {
	
	init: function () {
		
		try {
			
			var point = new google.maps.LatLng($("#map").data("lat"),$("#map").data("lon"));
			
			var marker;
			
			var myMapOptions = {
				zoom: 12,
				center: point,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			
			var image = new google.maps.MarkerImage(
				'/images/img_placeholder.png',
				new google.maps.Size(32,37),
				new google.maps.Point(0,0),
				new google.maps.Point(16,37)
			);			
			
			map = new google.maps.Map(document.getElementById("map"),myMapOptions);			
			
			
			$('.view-map').each(
				function(){
					point = new google.maps.LatLng($(this).data('lat'), $(this).data('lon'));
					marker = new google.maps.Marker({
						draggable: true,
						raiseOnDrag: false,
						icon: image,
						map: map,
						position: point
					});					
				}
			);
			
		}
		catch(e)
		{
			//***
		}
	},
	
	position: function (lat, lon) {
		
		try {
			
			var point = new google.maps.LatLng(lat, lon);
		
			map.panTo(point);
			map.setZoom(16);

		}
		catch(e) {
			//***
		}
	}
};

var dragX = 0;
var dragPosition = 0;
var dragUpdate;
var dragWidth;

var timeline = {
	
	init: function (event) {
		
		dragX		= event.pageX;
		dragWidth	= ($(".data").length * 90) - (parseInt($(".limiter").css("width"))-40);
	},
	
	update: function (option) {
		
		if(dragPosition > 0) {
			dragPosition = 0;
			$(".arrow-left").fadeOut();
		}
		else
		if(dragPosition < 0-dragWidth) {
			dragPosition = 0-dragWidth;
			$(".arrow-right").fadeOut();
		}
		else {
			$(".arrow-right").fadeIn();
			$(".arrow-left").fadeIn();
		}
		
		if(option == "drag") {
			$('#timelineContainer').css("left", dragPosition);
		}
		else {
			$('#timelineContainer').animate({
				left: dragPosition
			});
		}
	},
	
	drag: function (event) {
		
		dragPosition = parseInt($('#timelineContainer').css("left"));
		dragUpdate = (dragX - event.pageX)*4;
		dragPosition = dragPosition + dragUpdate;
		dragX = event.pageX;
		
		timeline.update("drag");
	},
	
	step: function (step) {
		
		dragPosition = parseInt($('#timelineContainer').css("left"));
		dragUpdate	 = step * 90;
		dragPosition = dragPosition + dragUpdate;
		
		timeline.update("animate");
	},
	
	ajust: function (position, columns) {
		
		var dragColumns = (dragPosition/90)*(-1);
		var diffColumns = position - dragColumns;
		
		if(diffColumns > 8) {
			dragUpdate	 = (diffColumns-8)*90;
			dragPosition = dragPosition - dragUpdate;
			timeline.update("animate");
		}
	}
};

var sort_left_right = {
	
	init: function () {
		
		setTimeout("sort_left_right.run()", 500);
		
	}, 
	
	run: function () {
		
		$('#sort_left_right li').each(function(index) {
			
			var height3rd = 0;
			var height4th = 0;
			
			console.log($("dl", this).offset().top)
			
    		if(index == 0) {
    			height1st = $("dl", this).offset().top;
    		} else if(index == 1) {
    			height2nd = $("dl", this).offset().top;
    		} else {
    			if(height1st > height2nd) {
    				
    				if($(this).hasClass("float-left")) {
    					$(this).removeClass("float-left");
    					$(this).addClass("float-right");
    				} else {
    					$(this).removeClass("float-right");
    					$(this).addClass("float-left");
    				}
    				
    			}
    		}
		});
		
	}
	
};

$(document).ready(function()
{
	$('body').addClass('js-enabled');
  
	//Start carouselShowcase
	//setTimeout(function () {
		carouselShowcase.setup('#showcase', 1, 'both');
		$("#showcase").mouseenter(carouselShowcase.showNav).mouseleave(carouselShowcase.hideNav);
//	}, 500); // Delay for IE
	
	//Start carouselInnovation//
//	setTimeout(function () {
		carouselInnovation.setup('#innovation', 1, 'both');
		$("#innovation").mouseenter(carouselInnovation.slideDown).mouseleave(carouselInnovation.slideUp);
//	}, 500); // Delay for IE
	
	//Start Thumbnail ImageSprite Carousel
	$(".thumb-animate").mouseenter(thumbAnim.start).mouseleave(thumbAnim.stop);
	
	//Javascript Commands
	$(".divSwap-displayInfo").click(function(e) {
		divSwap.displayInfo($(this).data('selector'));
		e.preventDefault();
	});
	$(".divSwap-scroll").click(function(e) {
		$("#description .yellow").removeClass('yellow').addClass('grey-dark');
		$(this).removeClass('grey-dark').addClass('yellow');
		divSwap.scroll($(this).data('selector'));
		e.preventDefault();
		//
		$('html, body').animate({scrollTop:155}, 300);
	});
	$(".divSwap-goToTop").click(function(e) {
		$("#description .yellow").removeClass('yellow').addClass('grey-dark');
		$(".first").removeClass('grey-dark').addClass('yellow');
		divSwap.scroll($(this).data('selector'));
		$('html, body').animate({scrollTop:0}, 300);

		e.preventDefault();
	});
	
	//Projects Image Swap
	
	$("#imagePrev").click(function (e) {
		imageSwap.prev($(this).data('total'));
		e.preventDefault();
	});
	$("#imageNext").click(function (e) {
		imageSwap.next($(this).data('total'));
		e.preventDefault();
	});
	$("#imageMain").click(function (e) {
		imageSwap.next($(this).data('total'));
		e.preventDefault();
	});
	$(".imageSwap-fade").click(function(e) {
		imageSwap.fade($(this).data('selector'));
		e.preventDefault();
		$('html, body').animate({scrollTop:155}, 300);
	});
	
	var zcounter = 999;
	
	//Timeline
	
	$("#timeline .available").mouseenter(function () {
		$(".year-big, .text1-bar, .text1, .time-click", this).addClass("time-this");
		
		//$(".ruler").not(".time-this").css("background", "url(/images/timeline_ruler.png) no-repeat 0 0");
		$(".text1").not(".time-this").animate({opacity:0}, 50);
		$(".time-click, .time-close").not(".time-this").fadeOut(200);
		
		//$(".ruler").not(".time-this").css("background", "url(/images/timeline_ruler.png) no-repeat 0 0");
		$(".year-big, .text1-bar, .text1", this).animate({opacity:1}, 200);
		
		
		$(".year-big, .text1-bar, .text1", this).css('z-index', zcounter++ );
		
		$(".time-this", this).removeClass("time-this");
	});
	
	$("#timeline .available").click(function (event) {
		
		$(".year-big, .text1-bar, .text1, .time-click", this).addClass("time-this");
		
		//$(".year-big, .text1-bar, .text1").not(".time-this").animate({opacity:0}, 200);
		$(".time-click").not(".time-this").fadeOut(200);
		
		$(".year-big, .text1-bar, .text1", this).animate({opacity:1}, 200);		
		$(".time-click, .time-close", this).fadeIn(200);
		$(".year-big, .text1-bar, .text1", this).css('z-index', zcounter++ );
		$(".time-click, .time-close", this).css('z-index', zcounter++ );
		
		timeline.ajust($(this).data("position"), $(this).data("columns"));
		//setTimeout(ajust, 200);
		
		$(".time-this", this).removeClass("time-this");
	});
	
	$("#timeline").mouseleave(function () {
		//$(".ruler").not(".time-this").css("background", "url(/images/timeline_ruler.png) no-repeat 0 0");
		$(".text1").not(".time-this").animate({opacity:0}, 200);
		$(".year-big, .text1-bar").not(".time-this").animate({opacity:1}, 200);		
		$(".time-click, .time-close").not(".time-this").fadeOut(200);
	});
	
	$("#timeline").mouseenter(timeline.init);
	//$("#timeline").mousemove(timeline.drag);
	$("#timeline .command1").click(function (e) {timeline.step(+5); e.preventDefault; }).mouseenter(function () { $("#timeline .arrow-left").css("background-position", "0 -16px") } ).mouseleave(function () { $("#timeline .arrow-left").css("background-position", "0 0") } );
	$("#timeline .command2").click(function (e) {timeline.step(-5); e.preventDefault; }).mouseenter(function () { $("#timeline .arrow-right").css("background-position", "-12px -16px") } ).mouseleave(function () { $("#timeline .arrow-right").css("background-position", "-12px 0") } );
	
	//Map
	if($("#map")){
	  contactMap.init();
	}
	$(".view-map").click(function(e) {
		contactMap.position($(this).data('lat'),$(this).data('lon'));
		e.preventDefault();
	});
	
	//Placeholder (Cross-Browser)
	
	$('[placeholder]').focus(function() {
	  var input = $(this);
	  if (input.val() == input.attr('placeholder')) {
		input.val('');
		input.removeClass('placeholder');
	  }
	}).blur(function() {
	  var input = $(this);
	  if (input.val() == '' || input.val() == input.attr('placeholder')) {
		input.addClass('placeholder');
		input.val(input.attr('placeholder'));
	  }
	}).blur();
	$('[placeholder]').parents('form').submit(function() {
	  $(this).find('[placeholder]').each(function() {
		var input = $(this);
		if (input.val() == input.attr('placeholder')) {
		  input.val('');
		}
	  })
	});
	
	//Inspiration Sort
	
	sort_left_right.init();
});
