/* 
Table of Contents:

	- Twitter
	- Toggle inputs
	- Global navigation
	- Hover fade
	- Coins slider
	- Preload images
	- Paper slider
	- Services tabs
	- Testimonials tabs
	- Portfolio layout switcher
	- Portfolio filter
	- Portfolio previewer
	- Contact form
	- Tooltips
	- Font replacement
	- Misc
*/

$(document).ready(function(){

	/* Twitter
	--------------------------------------------------------------------------------------- */
	
	var twiterName = "cmtstudio"; // Insert your username here
	var twitterHead = '<a href="http://twitter.com/' + twiterName + '" class="twicon"><img src="images/icon_twitter.png" alt="" /></a>';
	
	$('#latest-tweet').getTwitter({
		userName: twiterName,
		numTweets: 1,
		loaderText: 'Loading tweets...',
		slideIn: false,
		showProfileLink: false,
		headingText: twitterHead,
		showTimestamp: false
	});


	/* Toggle inputs
	--------------------------------------------------------------------------------------- */

	function toggle_input(selector) { // Hide placeholder on focus, show it on blur
		var value = selector.val();
		selector.focus(function() {
			if ($(this).val() == value)
				$(this).val("");
		}).blur(function() {
			if ($(this).val() == "")
				$(this).val(value)
		});
	}

	var name = $("#newsletter input:nth-child(1)"); // The "Name" input
	var mail = $("#newsletter input:nth-child(2)"); // The "E-mail" input
	toggle_input(name);
	toggle_input(mail);
	
	
	/* Global navigation
	--------------------------------------------------------------------------------------- */
	
	$("#global-nav>li>ul").addClass("sub-away").show().hide(); // Remove CSS interaction and hide
	$("#global-nav>li").has("ul.sub-away").hover(
		function(){
			$(this).children("ul").stop(false, true).fadeIn(500).animate({top: 71}, {duration: 200, queue: false});
		}, function(){
			$(this).children("ul").stop(false, true).fadeOut(100).animate({top: 120}, {duration: 200, queue: false});
		}
	);
	
	// Second level submenus
	$("#global-nav ul ul").show().hide();
	$("#global-nav ul li").has("ul").hover(
		function(){
			$(this).children("ul").stop(false, true).slideDown("fast");
		}, function(){
			$(this).children("ul").stop(false, true).slideUp("fast");
		}
	);
	

	/* Hover fade
	--------------------------------------------------------------------------------------- */

	function hover_fade(selector, speed, trans) {
		$(selector)
			.fadeTo(speed, trans)
			.hover(
				function(){ // On mouseover - full opacity
					$(this).fadeTo(speed, 1).dequeue();
				},
				function(){ // On mouseout - restore opacity
					$(this).fadeTo(speed, trans);
				}
			);
	}
	
	// Fade on hover - social icons and blog related posts
	hover_fade("#social li", "fast", 0.3);
	hover_fade(".related img", "fast", 0.7);

	// Contact social icons fade
	var speed = "fast";
	var trans = 0.6;
	$("ul.social li span").fadeTo(speed, trans);
	$("ul.social a").hover(
		function(){ // On mouseover - full opacity
			$(this).children("span").fadeTo(speed, 1).dequeue();
		},
		function(){ // On mouseout - restore opacity
			$(this).children("span").fadeTo(speed, trans);
		}
	);


	/* Coin slider (c) CMT Studio
	--------------------------------------------------------------------------------------- */
	
	var animationSpeed = 600; 	// Transition duration
	var rotationSpeed = 4000; 	// Slideshow speed
	
	var singleSlide = $(".single-slide"); // Count slides to dynamically add coins for them
	var numberOfSlides = singleSlide.size();
	
	if (numberOfSlides > 1) { // Don't show arrows/coins for just one slide
		$("#slider-mid").append('<a id="slide-prev" href="#"></a> <!-- previous slide arrow --><a id="slide-next" href="#"></a> <!-- next slide arrow -->'); // Add the coin slider arrows
		var slidesControl = $("#slider-controls ul");
		slidesControl.css({width: numberOfSlides * 17}); // Width of coins list
		
		var i;
		for (i = 0; i < numberOfSlides; i++) {
			var slideTitle = singleSlide.eq(i).find("h2").text(); // Use the h2 for the coin title
			slidesControl.append('<li><a href="#slide-' + (i+1) + '" title="' + slideTitle + '"></a></li>'); // Add slider controls
			singleSlide.eq(i).attr("id", "slide-" + (i+1)); // Assign id to each slide
		}
		
		// Coins interaction
		var slideAnchors = $("#slider-controls a");
		var slideWidth = $("#slider-mid").width();
	
		slideAnchors.eq(0).addClass("active");
		slideAnchors.bind("click", function(){
			slideAnchors.removeClass("active");
			$(this).addClass("active"); // Assign active class to clicked coin
			var slideIndex = $(this).attr("href").split("#slide-")[1]; // Which slide to show
			var slideOffset = -1 * (parseInt(slideIndex)-1) * slideWidth;
			$("#slider-mid>ul").stop().animate({marginLeft: slideOffset }, animationSpeed);
			return false;
		});
		
		// Arrows interaction, slideshow
		function triggerPrev() {
			var prevSlide = parseInt($("#slider-controls a.active").attr("href").split("#slide-")[1]) - 1;
			if (prevSlide === 0) {
				prevSlide = numberOfSlides;
			}
			slideAnchors.removeClass("active");
			slideAnchors.eq(--prevSlide).addClass("active"); // Eq() is zero-based, prevSlide is not
			var slideOffset = -1 * (prevSlide) * slideWidth;
			$("#slider-mid>ul").stop().animate({marginLeft: slideOffset }, animationSpeed);
		}
		function triggerNext() {
			var nextSlide = parseInt($("#slider-controls a.active").attr("href").split("#slide-")[1]) + 1;
			if (nextSlide > numberOfSlides) {
				nextSlide = 1;
			}
			slideAnchors.removeClass("active");
			slideAnchors.eq(--nextSlide).addClass("active"); // Eq() is zero-based, nextSlide is not
			var slideOffset = -1 * (nextSlide) * slideWidth;
			$("#slider-mid>ul").stop().animate({marginLeft: slideOffset }, animationSpeed);
		}
		
		// Arrows interaction
		$("#slide-prev").bind("click", function(){
			triggerPrev();
			return false;
		});
		$("#slide-next").bind("click", function(){
			triggerNext();
			return false;
		});
		
		// SlideShow
		var slideShow = setInterval(triggerNext, rotationSpeed); // Start the slideshow
		$("#slider-mid, #slider-controls").hover(
			function(){
				clearInterval(slideShow); // Stop the slideshow on mouseover
			},
			function(){
				slideShow = setInterval(triggerNext, rotationSpeed); // Start the slideshow on mouseout
			}
		);
	}
	
	
	/* Paper slider (c) CMT Studio
	--------------------------------------------------------------------------------------- */
	
	// Settings
	var pRotation;
	var pFadeSpeed = 400; 		// Thumbnails fade speed
	var pFadeOpacity = 0.4; 	// Inactive thumbnails opacity
	var pRotationSpeed = 3500; 	// Slideshow speed
	var pMethod = "fade"; 		// Choose between "fade" and "hide"
	
	// Slideshow
	function paperRotation() {
		pRotation = setInterval(function(){
			var nextThumb = $("#p-carousel .active").parent("li").next().children("a");
			if (nextThumb.length == 0) {
				nextThumb = $("#p-carousel a:first");
			}
			
			pSlides.stop().pAnimate(pFadeSpeed, 0); // Hide all slides
			
			var nextSlide = $(nextThumb).attr("href");
			
			// IE7 gets the full href, instead of only the "#" part - so extract it
			if ( ($.browser.msie && parseInt($.browser.version) == 7) ) {
				nextSlide = "#" + nextSlide.split("#")[1];
			}
			$(nextSlide).pAnimate(pFadeSpeed, 1); // Fade in the next slide
			pThumbs.removeClass("active").children("img").stop().fadeTo(pFadeSpeed, pFadeOpacity);
			nextThumb.addClass("active").children("img").stop().fadeTo(0, 1);
		}, pRotationSpeed);
	}		

	/* Preload images	Credits: pogoking - http://twitter.com/pogoking
	--------------------------------------------------------------------------------------- */	
	var firstTimeRotation = true;
	$.fn.preloadImages = function(options){

		var defaults = {
			showSpeed: 500
		};
		
		var options = $.extend(defaults, options);
		return this.each(function(){
			var container = $(this);
			var image = container.find("img");
			$(image).css({ visibility: "hidden", opacity: 0 });
			$(image).bind('load error', function(){ // Images are loaded
				$(this)
					.css({ visibility: "visible" })
					.animate({ opacity: 1 }, { duration:options.showSpeed })
					.parent(container);
					if (firstTimeRotation && $("#pslider").length > 0)// Start rotation only once
						paperRotation();
					firstTimeRotation = false;
					$(".preload").removeClass("preload");
			}).each(function(){
				if ( this.complete || ($.browser.msie && parseInt($.browser.version) == 6) ) {
					$(this).trigger('load');
				}
			});
		});
	}
	
	// Preload all images before starting out the slideshow
	$(".preload").preloadImages();
	
	// pAnimate applies either "fade" or "hide"
	$.fn.extend({
		pAnimate: function(speed, value) {
			if (pMethod == "fade") {
				$(this).fadeTo(speed, value);
			} else if (pMethod == "hide") {
				if (value == 0) {
					$(this).hide(speed);
				}
				else if (value == 1) {
					$(this).show(speed);
				}
			}
		}
	});
	
	var pSlides = $("#pslider li");
	var pControls = $("#p-carousel");
	var pNumOfSlides = pSlides.size();
	
	// Create thumbnails, set interactions (mouseover, mouseout, click)
	if (pNumOfSlides > 1) {
		// Set slider markup and presentation
		pControls.css({width: pNumOfSlides * 124}); // Dynamically set thumbnails list width
		var i;
		for (i = 0; i < pNumOfSlides; i++) {
			var pThumbSrc = pSlides.eq(i).find("img").attr("src");
			var pTitle = pSlides.eq(i).find("a.text").text(); // Use text for thumbs title

			pControls.append('<li><a href="#slide-' + (i+1) + '" title="' + pTitle +'"><img src="' + pThumbSrc + '" alt="' + pTitle +'" /></a></li>'); // Add control thumbnails
			pSlides.eq(i).attr("id", "slide-" + (i+1)); // Assign id to each slide
		}
		
		// Interaction
		var pThumbs = $("#p-carousel a");
		
		pThumbs.children("img").fadeTo(pFadeSpeed, pFadeOpacity);
		pThumbs.eq(0).addClass("active").children("img").fadeTo(pFadeSpeed, 1.0);
		
		pThumbs.bind("click", function(){
			if ( !$(this).hasClass("active") ) { // Don't do anything if user clicks on active thumb
				pSlides.stop(false, true).pAnimate(pFadeSpeed, 0); // Hide all slides
				var activeSlide = $(this).attr("href");
				
				// IE7 gets the full href, instead of only the "#" part - so extract it
				if ( ($.browser.msie && parseInt($.browser.version) == 7) ) {
					activeSlide = "#" + activeSlide.split("#")[1];
				}
				
				$(activeSlide).stop(false, true).pAnimate(pFadeSpeed, 1); // Show active slide
				
				pThumbs.removeClass("active");
				$(this).addClass("active").children("img").fadeTo(0, 1); // Fade in active thumb
				pThumbs.not(".active").children("img").fadeTo(pFadeSpeed, pFadeOpacity); // Fade out all thumbs but the active
			}
			
			return false;
		});
		
		pSlides.hide().eq(0).pAnimate(pFadeSpeed, 1); // Show the first slide
		
		$("#p-carousel a, #pslider li").hover(
			function() {
				clearInterval(pRotation); // Stop the slideshow on mouseover
				if ( !$(this).hasClass("active") )
					$(this).children("img").stop().fadeTo(pFadeSpeed, 1);
			}, function() {
				paperRotation(); // Start the slideshow on mouseout
				if ( !$(this).hasClass("active") )
					$(this).children("img").stop().fadeTo(pFadeSpeed, pFadeOpacity);
			}
		);
	}


	/* Services tabs (homepage)
	--------------------------------------------------------------------------------------- */
	var serviceSpeed = 400;
	
	var serviceNav = $(".service-tabs a");
	var serviceContent = $("#homeproj .single-content");
	
	serviceContent.hide();
	serviceContent.eq(0).show();
	serviceNav.eq(0).addClass("active"); 			// "Activate" first class
	
	serviceNav.bind("click", function(){
		if ( ! $(this).hasClass("active") ) {			
			serviceNav.removeClass("active"); 		// Remove active class on all tabs
			$(this).addClass("active"); 			// Add active class on clicked tab
			
			var activeTab = $(this).attr("href"); 	// Find href of clicked tab
			serviceContent.slideUp(serviceSpeed); 	// Hide all content
			$(activeTab).slideDown(serviceSpeed); 	// Slide down the clicked content
		}
		return false;
	});


	/* Testimonials slide (homepage)
	--------------------------------------------------------------------------------------- */
	
	testimSpeed = 500;
	
	var testimContent = $("#home-testim li");
	testimContent.hide(); 							// Hide all
	testimContent.eq(0).show().addClass("active"); 	// Show first
	
	$("#slide-testim a").bind("click", function(){
		// If clicked the prev button and it's not the first testimonial
		if ( $(this).hasClass("prev") ) {
			var prevTestim = $("#home-testim li.active").prev(); // Get previous item
			if ( prevTestim.length == 0 ) { // End of slider, quit
				return false;
			}
			
			testimContent.removeClass("active").stop(false, true).hide(speed); // Reset classes, hide all
			prevTestim.addClass("active").stop(false, true).show(testimSpeed); // Show selected
		}
		
		// If clicked the next button and it's not the last testimonial
		if ( $(this).hasClass("next") ) {
			var nextTestim = $("#home-testim li.active").next(); // Get next item
			if ( nextTestim.length == 0 ) { // End of slider, quit
				return false;
			}
			
			testimContent.removeClass("active").stop(false, true).hide(speed); // Reset classes, hide all
			nextTestim.addClass("active").stop(false, true).show(testimSpeed); // Show selected
		}
		return false;
	});
	
	
	/* Portfolio filter
	--------------------------------------------------------------------------------------- */
	
	function filterPortfolio(thisCat) {
		var animateSpeed = 400;									// How fast to show/hide items
		
		var filterNav = $(".portcats a"); 						// The filter navigation
		var filterContent = $(".port-det>li"); 					// The portfolio items
		var selectedCat = thisCat.attr("href").split("#")[1]; 	// What category did you click on?
		
		if ( !thisCat.hasClass("active") ) { 	// Don't do anything if clicked on "active" tab
			filterNav.removeClass("active"); 	// Reset all items
			thisCat.addClass("active"); 		// Clicked item is now the active
			
			if ( selectedCat == "all" ) {
				var toDisplay = ".port-det>li";
				
				$(toDisplay)
					.addClass("visible")	// Needed for the layout switcher below
					.stop(false, true)
					.show(animateSpeed); 	// Show all items
			} else {
				var toDisplay = ".port-det>li[data-id*=" + selectedCat +"]"; // Filter items with selected "data-id"
				
				filterContent
					.removeClass("visible")	// Needed for the layout switcher below
					.stop(false, true)
					.hide(animateSpeed);	// Hide all items
				$(toDisplay)
					.addClass("visible")	// Needed for the layout switcher below
					.stop(false, true)
					.show(animateSpeed); 	// Show items from selected category
				
			}
			
			// Correct padding of first items
			filterContent.removeClass("first");
			if ( $(".port-det").hasClass("port-thumb") ) { 	// For thubnails-type layout
				$(toDisplay).filter(function(index){ return index % 3 == 0; }).addClass("first");
			} else { 										// For details-type layout
				$(toDisplay).eq(0).addClass("first");
			}
		}
	}
	$(".portcats a").bind( "click", function(){
		filterPortfolio($(this));
		return false;
	} );
	
	/* Portfolio layout switcher
	--------------------------------------------------------------------------------------- */
	
	$(".port-switch").bind("click", function(){
		var portContent = $(".port-det");
		
		// Toggle layout style
		if ( $(this).hasClass("details") ) {	// If the current layout is "details", switch to "thumbs"
			$(this).removeClass("details"); 		// Change switcher button
			portContent.addClass("port-thumb"); 	// Change layout
		} else {								// If the current layout is "thumbs", switch to "details"
			$(this).addClass("details");			// Change switcher button
			portContent.removeClass("port-thumb"); 	// Change layout
		}
		
		// Filter only visible items
		var portItems = $(".port-det>li");
		var filteredItems = $(".port-det>li.visible");
		if (filteredItems.length == 0) {	// No filter has been applied yet => everything is visible
			filteredItems = portItems;
		}
		
		if ( $(this).hasClass("details") ) { // "Details" layout => correct padding of first item
			filteredItems = filteredItems.eq(0);
		} else {							// "Thumbnails" layout => correct paading of every third item
			filteredItems = filteredItems.filter(function(index){
				return index % 3 == 0;		// Filter every third item
			});	
		}
		
		portItems.removeClass("first")		// Reset classes
		filteredItems.addClass("first");	// Correct padding
		
		return false;
	});
	
	
	/* Portfolio previewer
	--------------------------------------------------------------------------------------- */
	
	var projMain = $(".proj-main");
	var projThumbs = $(".proj-thumbs a");

	projThumbs.eq(0).addClass("active"); // "Activate" first thumbnail
	
	projThumbs.bind("click", function(){
		if ( ! $(this).hasClass("active") ) { // Don't do anything if user clicks on active thumbnail
			
			// Change image before animation
			$("img", projMain).attr("src", "images/proj-main.jpg");
			
			// Toggle classes
			projThumbs.removeClass("active");
			$(this).addClass("active");
			
			// Get url and title of clicked image
			var activeImg = $(this).attr("href");
			var activeTitle = $(this).attr("original-title");
			if ( typeof activeTitle == "undefined" ) // If the Tipsy plugin is inactive
				activeTitle = $(this).attr("title");
			
			// Get image height
			var img = new Image();
			img.src = activeImg;
			img.onload = function(){
				// Calculate the main image height for the animation
				var mainImgWidth = projMain.width();
				var imgRatio = img.width / mainImgWidth;
				var mainImgHeight = img.height / imgRatio;
				
				// Animate and replace main image
				$("img", projMain).stop().animate({height: (img.height) / imgRatio }, function(){
					var attrMap = { href: activeImg, title: activeTitle };
					$("a", projMain).attr(attrMap);
					$("img", projMain).attr("src", activeImg);
				});
			};
			
		}
		
		return false;
	});
	
	// Fade main image on hover
	var projFade = 0.5;
	var projSpeed = 300;	
	
	$(".proj-main a, #gmap-content, .thickbox>img").hover(
		function(){
			$(this).fadeTo(projSpeed, projFade);
		}, function(){
			$(this).fadeTo(projSpeed, 1);
		}
	);

	/* Contact form
	--------------------------------------------------------------------------------------- */
	$("form.contact").submit(function(e){
		e.preventDefault();
		$.post('mail.php', $(this).serialize(), function(data) {
				handleForm(data);
		}, "html");
	});
	
	// Handle form data
	function handleForm(data) {
		var feedback = $("#sent-feedback");
		feedback.removeClass().html(data).slideDown(); // Show the message container
		var isError = ( feedback.children(".error").length > 0 ) ? true : false;
		var isSuccess = ( feedback.children(".success").length > 0 ) ? true : false;
		
		if ( isError ) {
			feedback.addClass("error");
		}
		if ( isSuccess ) {
			feedback.addClass("success");
		}
	}
	
	// Form slider
	if ( typeof $(window).slider == "function"  ) {		// Check if the jQuery UI script is included
		var uiSliderMax = 50000;	// Starting value
		var uiSliderMin = 0;		// Ending value
		var uiSliderStep = 1000;	// Value for fixed incrementing when sliding
		var uiSliderValue = 1000;	// Initial value, when the page loads
		
		$(".ui-slider").append('<small id="ui-value" />').slider({
			animate: true,
			min: uiSliderMin,
			max: uiSliderMax,
			step: uiSliderStep,
			value: uiSliderValue,
			slide: function(event, ui) {
				var uiValue = $("#ui-value");
				
				if (ui.value != uiSliderMin) { 						// Don't show value if handler moved leftmost
					uiValue.html("$" + ui.value); 					// Change value
					$(this).children("input").val("$" + ui.value);	// Copy slider value to original input
				} else {
					uiValue.html("");
					$(this).children("input").val("");
				}
			}
		}).children("input").hide(); // Hide original input
		
		// Initialize if there is some value, different from the minimum
		var sliderValue = $(".ui-slider").slider("value");
		if ( uiSliderValue != uiSliderMin ) {
			$("#ui-value").html("$" + sliderValue);
			$(".ui-slider input").val("$" + sliderValue);
		}
	}
	
	// jqTransform
	$("form.contact").jqTransform();
	
	
	/* Tooltips
	--------------------------------------------------------------------------------------- */

	// Coinslider and paperslider controls
	$("#slider-controls a, #p-carousel a").tipsy({
		gravity: "n",
		offset: 20
	});

	// Homepage intro links
	$(".home-intro p a").tipsy();
	
	// Homepage service tab images
	$("#homeproj ul a").tipsy({
		html: true,
		offset: 20,
		title: function() {
			var img = $(this).attr("data-value");
			var title = '<div class="img-wrap"><img src="' + img +'" alt="" /></div>';
			title += '<strong>';
			title += $(this).attr("original-title");
			title += '</strong>';
			
			return title;
		}
	});
	
	// Services images
	$(".services ul a").tipsy({
		gravity: "w",
		html: true,
		offset: 20,
		title: function() {
			var img = $(this).attr("data-value");
			var title = '<div class="img-wrap"><img src="' + img +'" alt="" /></div>';
			title += '<strong>';
			title += $(this).attr("original-title");
			title += '</strong>';
			
			return title;
		}
	});
	
	// RSS and mail subscriptions (top footer)
	$("#rss-sub, #mail-sub").tipsy({
		gravity: "e",
		offset: 10,
		html: true
	});
	
	// Single portfolio: preview thumbnails, previous/next project; Single blog: social sharing
	$(".proj-thumbs a, .share-post li a, #proj-change a").tipsy({
		gravity: "n",
		offset: 10
	});
	
	
	/* Font replacement
	--------------------------------------------------------------------------------------- */
	
	Cufon.replace("h1:not(.nocufon), h2, h3:not(.nocufon), h4:not(.nocufon), .blog-post h5, .author h5, .blog-post h6, .blog-com h6, .home-intro p", {
		hover: true
	});

	// Increase font after replacing it with Cufon
	$("#home-intro p").css({'font-size' : '30px'});
	
	
	/* Misc
	--------------------------------------------------------------------------------------- */

	// Fix submit buttons for Safari only - reset Chrome margin
	var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
	if ( isChrome ) {
		$("button span").css("margin-left", "0")
	}
});
