/* Author: Ayesha Lomaski & Tales Cione
*/

var currentPage = (window.location.hash === "") ? '#home' : window.location.hash,
	haveLoadedGT480 = false;

var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& 
var isiOS = DetectIphoneOrIpod();


$(function(){
	var refreshPage = false;

	$(window).bind('hashchange', function() {
		if(refreshPage) {
			window.location.reload(true);
		}

		if(window.location.hash.charAt(1) === '!')
			refreshPage = true;
			
	});

	if($(window).width() > 960) resizeNavItems();


	$(".search .blog-page .clients-wrapper .clients-cell:lt(2)").hide();


	if($(window).width() > 480) {
		haveLoadedGT480 = adjustFunctionsGT480();
	} else {
		// width < 480
		// var sdbHomeHTML = $('.sidebar-home-wrapper').html(),
		// 	sdbContHTML = $('.sidebar-contato-wrapper').html(),
		// 	sdbFormHTML = $('.contact-form').html();
		
		// $('aside').hide();
		// $('<div class="mob-cases"></div>').html(sdbHomeHTML).appendTo('#home');

	}

	/*************************
	 * Paginacao do blog
	 ************************/
	 $(".blogroll").delegate("a.more","click", function(e){
	 	var paged = $(this).attr("page");
	 	$(this).html("<span id='spinner-load'></span>");

	 	/* "<span id='spinner-load'></span>" */
		var warp = 0;
		var t = window.setInterval(function(){
			if(warp > -385) {
				warp -= 35;
			} else {
				warp = 0;
			}
			$('#spinner-load').css('backgroundPositionY', warp);
		}, 100);

	 	$.ajax({
	 		type: "POST",
	 		data:"paged="+paged,
			url: '?page_id=3562',
			success: function(html) {
				clearInterval(t);
				if(html === "naotem") {
					$("a.more").fadeOut();
				} else {
					$(html).insertBefore("a.more");
					$("a.more:last").remove();
				}
			}
		});
	 });

	/*************************
	 * Load Cases 
	 ************************/

	$(".sidebar-home-wrapper .clients").click(function(){

		var postid = $(this).attr("data-id");
		var postslug = $(this).attr('data-slug');
		$("#case").html("<span id='spinner-load'></span>").show();

		/* "<span id='spinner-load'></span>" */
		var warp = 0;
		var t = window.setInterval(function(){
			if(warp > -385) {
				warp -= 35;
			} else {
				warp = 0;
			}
			$('#spinner-load').css('backgroundPositionY', warp);
		}, 100);

		$.ajax({
	 		type: "POST",
	 		data:"postid="+postid,
			url: '?page_id=85',
			success: function(html) {
				clearInterval(t);

				if($(window).width() > 480) {
					$('#case').css('left', $(window).width());

					$("#case").html(html);



					$('#case').animate({
						'left': 0
					}, 500);

					$('header hgroup h1').html('CASES');
					$('header hgroup h2').html('');
				} else {
					$("#case").hide().html(html);
					$('a.volta').html('X');
					var content = $("#case").html();
					$('#case').remove();
					var newContent = '<div id="case" role="page">' + content + '</div>';
					$(newContent).hide().insertAfter('.clients[data-id="'+postid+'"]').slideDown(500);
				}

				if ($(window).width() > 540){
					generateScroll(3);
					window.location.hash = '!/cases/' + postslug;
				}
			}
		});
	});

	$("#case").delegate("a.volta","click",function(){
		if($(window).width() > 480) {
			$("#case").animate({
				'left': $(window).width()
			}, 500);
		} else {
			$("#case").slideUp(500);
		}
		refreshPage = false;
		window.location.hash = 'home';
		$('header hgroup h1').html('SOMOS');
		$('header hgroup h2').html('uma agência focada<br/><span>em mídias sociais e</span><br/>relacionamentos na rede');
	});

	/** **/

	$(window).resize(function(){

		if(!haveLoadedGT480 && $(window).width() > 480) {
			$('body').removeClass('sim-mobile');
			haveLoadedGT480 = adjustFunctionsGT480();
		} else if(!isAndroid && !isiOS)  {
			$('body').addClass('sim-mobile');
			
			haveLoadedGT480 = false;
		} else {
			haveLoadedGT480 = false;
		}

		if ($(window).width() > 960) resizeNavItems();
		
	});

	$("form.contact-form").validate();

	$("form.contact-form").submit(function(e){
		$(".contact-form .cf-sent p").html("<span id='spinner-load-dark'></span>");


		/* "<span id='spinner-load'></span>" */
		var warp = 0;
		var t = window.setInterval(function(){
			if(warp > -385) {
				warp -= 35;
			} else {
				warp = 0;
			}
			$('#spinner-load').css('backgroundPositionY', warp);
		}, 100);

		if($("form.contact-form").valid()){
			var data = $(this).serialize();
			$.ajax({
				type:"POST",
				data: data,
				url: "http://www.cwksp.ws/coworkers/contact-ajax.php",
				complete: function(html){
					clearInterval(t);
					$(".contact-form .cf-sent p").html("Mensagem enviada com sucesso!");
				}
			});
		}
		return false;
	});


});

function adjustFunctionsGT480()
{
	var currentPos = 0,
		descricao = 'uma agência focada<br/><span>em mídias sociais e</span><br/>relacionamentos na rede',
		titles = {
			'#home': {
				'name': 'SOMOS',
				'desc': descricao
			},
			'#o-que-fazemos': {
				'name': 'O QUE FAZEMOS',
				'desc': ''
			},
			'#clientes': {
				'name': 'CLIENTES',
				'desc': ''
			},
			'#contate': {
				'name': 'CONTATO',
				'desc': ''
			},
			'#blog': {
				'name': 'BLOG',
				'desc': ''
			}
		};

	var currentPageType = currentPage.charAt(1) === '!' ? 'case' : 'regular';


	$('.so-lazy').lazyLoad();

	if(currentPage === '#home') {
		$('.sidebar-contato-wrapper').css('display', 'none');
		$('.contact-form').css('marginTop', -1368);
	} else if(currentPage === '#contate') {
		$('.sidebar-home-wrapper').css('display', 'none');
		$('.sidebar-contato-wrapper').css('display', 'block');
		$('.contact-form').css('marginTop', -625);
	} else {
		if(currentPageType !== 'case') $('aside').css('display', 'none');	
	}

	if(currentPageType === 'case') {
		$('header hgroup h1').html('CASES');
		$('header hgroup h2').html('');

		var currentCase = currentPage.split('/'),
			currentCase = currentCase[2];

		var postid = $('.clients[data-slug="'+ currentCase +'"]').attr("data-id");
		var postslug = currentCase;
		$("#case").html("<span id='spinner-load'></span>").show();

		/* "<span id='spinner-load'></span>" */
		var warp = 0;
		var t = window.setInterval(function(){
			if(warp > -385) {
				warp -= 35;
			} else {
				warp = 0;
			}
			$('#spinner-load').css('backgroundPositionY', warp);
		}, 100);
		$.ajax({
	 		type: "POST",
	 		data:"postid="+postid,
			url: '?page_id=85',
			success: function(html) {
				clearInterval(t);

				if($(window).width() > 480) {
					$("#case").html(html).fadeIn(500);
					$('header hgroup h1').html('CASES');
					$('header hgroup h2').html('');
				} else {
					$("#case").hide().html(html);
					$('a.volta').html('X');
					var content = $("#case").html();
					$('#case').remove();
					var newContent = '<div id="case" role="page">' + content + '</div>';
					$(newContent).hide().insertAfter('.clients[data-id="'+postid+'"]').slideDown(500);
				}

				window.location.hash = '!/cases/' + postslug;
				
			}
		});
	}

	if(titles[currentPage] != undefined) {
		$('header hgroup h1').html(titles[currentPage].name);
		$('header hgroup h2').html(titles[currentPage].desc);
	}

	
	$('#home').css('height', $(window).height());

	winTimeout = ' ';
	$(window).resize(function() {
		if($(window).height() > 480) {
			if(winTimeout !== ' ') clearTimeout(winTimeout);

			$('#home').css('height', $(window).height());

			var currentY = $(currentPage).offset(),
				currentY = currentY.top;

			winTimeout = setTimeout(function(){ 
				$("html:not(:animated),body:not(:animated)").animate({ scrollTop: currentY}, 1 );
				winTimeout = ' ';
			}, 100);
		}
	});

    $('body').mousewheel(function() {
		return false;
	});

	if ($(window).width() > 500){
			generateScroll(0);
			generateScroll(1);
			generateScroll(2);
			generateScroll(3);
			generateScroll(4);
	}

	$('header nav.default a').click(function(){
		var elementClicked = $(this).attr('href'),
	   		destination = $(elementClicked).offset().top;
	   	
	   	currentPage = elementClicked;

	   	$('header hgroup h1').html(titles[currentPage].name);
		$('header hgroup h2').html(titles[currentPage].desc);
		$("#case").fadeOut("slow");

		// if(currentPage === '#contate') {
		// 	$('.contact-form').css('marginTop', -625);
		// } else {
		// 	$('.contact-form').css('marginTop', -548);
		// }

		if(currentPage === '#home') {
			$('.sidebar-contato-wrapper').css('display', 'none');
			$('.contact-form').css('marginTop', -1368);
		} else if(currentPage === '#contate') {
			$('.sidebar-home-wrapper').css('display', 'none');
			$('.sidebar-contato-wrapper').css('display', 'block');
			$('.contact-form').css('marginTop', -625);
		} else {
			if(currentPageType !== 'case') $('aside').css('display', 'none');	
		}

	   	if (elementClicked !== '#home' && elementClicked !== '#contate') {
	   		$('aside').fadeOut(500);	
	   	} else {
	   		$('aside').fadeIn(500);
	   		
	   		if(elementClicked === '#home') {
	   			$('.sidebar-home-wrapper').fadeIn(500);
	   			$('.sidebar-contato-wrapper').fadeOut(500);
	   		} else {
	   			$('.sidebar-home-wrapper').fadeOut(500);
	   			$('.sidebar-contato-wrapper').fadeIn(500);
	   		}
	   	}
	   	

		$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 500 );
		window.location.hash = currentPage;
		return false;
	});

	/*************************
	 * NAVIGATION 
	 ************************/

	if ($(window).width() > 960) {
		$("header nav.default a").each(function(){
			var left = ($(this).outerWidth() - 30) * -1;
			$(this).stop().animate({"left": left}, 500);
		});
	
		$("header nav.default a").hover(function(){
			var iconRight = $(this).outerWidth() - 26 - 1 ;
	
		  	$(this).stop().animate({"left": 0}, 500);
		  	$(this).children('.icon').fadeOut(500);
		},function(){
			var left = ($(this).outerWidth() - 30) * -1,
				iconRight = $(this).outerWidth() - 5;
	
			$(this).stop().animate({"left": left}, 500);
			$(this).children('.icon').fadeIn(500);
		});
	}


	/*************************
	 * SIDEBAR 
	 ************************/
	

	/*************************
	 * SIDEBAR FORM
	 ************************/
	$('body').delegate('.fill-the-form', 'click', function(){

		$('.contact-form').css('opacity', 0);

		$('.sidebar-contato-wrapper,.sidebar-home-wrapper')
		 .animate({
		 	'marginLeft': -325,
		 	'opacity': 0
		 }, 700);

		$('.contact-form').animate({
			'marginRight': 406,
			'opacity': 1
		}, 700);

		return false;
	});

	$('body').delegate('.form-voltar', 'click', function(){
		$('.contact-form').animate({
			'marginRight': 75,
			'opacity': 0
		}, 700);

		$('.sidebar-contato-wrapper,.sidebar-home-wrapper')
		 .animate({
		 	'marginLeft': 0,
		 	'opacity': 1
		 }, 700);
		

		return false;
	});
}

function resizeContainer(selector, treshold, width)
{
	var headerH = 110,
		footerH = 16,
		occH = (arguments[3]) ? 0 : headerH + footerH,
		leftH = $(window).height() - occH,
		noScroll = ($(window).height() < treshold ? false : true);
	
	$(window).resize(function() {

		var winHeight = $(window).height();

		if (winHeight > 480) {
			leftH = winHeight - occH;
			
			noScroll = (winHeight < treshold ? false : true);
			

			$(selector).css('height', leftH);
		
		
			if (!noScroll)
				$(selector).css({
					'overflowX' : 'hidden',
					'overflowY': 'hidden'
				});
			else
				$(selector).css('overflow', 'hidden');
		}


	});

	$(selector).css('height', leftH);
	
	if(!noScroll) 
		$(selector).css({
			'overflowX' : 'hidden',
			'overflowY': 'hidden'
		});

	var settings = {
		autoReinitialise: true,
		showArrows: false,
		contentWidth: width,
		hideFocus: true
	};

	$(selector).jScrollPane(settings);

	return true;
}

function generateScroll(pos)
{
	var height = $(window).height() + 10,
		wid = $(window).width() - 10;

	switch (pos)
	{
		case 0: 
			resizeContainer('.sidebar-home', 835, 340);
			break;

		case 1:
			resizeContainer('.blogroll', 2000, wid, true);
			break;

		case 2:
			resizeContainer('.oquefazemos', 740, wid, true);
			break;

		case 3:
			resizeContainer('.cases .txtbody', 600, wid, true);
			break;

		case 4:
			resizeContainer('.clients-wrapper', 835, wid, true);
			break;
		case 5: 
			resizeContainer('.sidebar-home', 835, 340);
			break;
		
		default:
			resizeContainer('.sidebar-home', 835, 340);
			break;	
	}
}




//**************************
// Detects if the current device is an iPhone.
function DetectIphone()
{
	var deviceIphone = "iphone";
   if (ua.search(deviceIphone) > -1)
      return true;
   else
      return false;
}

//**************************
// Detects if the current device is an iPod Touch.
function DetectIpod()
{
	var deviceIpod = "ipod";
   if (ua.search(deviceIpod) > -1)
      return true;
   else
      return false;
}

//**************************
// Detects if the current device is an iPhone or iPod Touch.
function DetectIphoneOrIpod()
{
    if (DetectIphone())
       return true;
    else if (DetectIpod())
       return true;
    else
       return false;
}

function resizeNavItems()
{
	if($(window).width()>480){

		var headerH   = 110,
			footerH   = 16,
			occH      = headerH + footerH,
			leftH     = $(window).height() - occH,
			navH      = leftH / 5,
			inneNavH  = $("header nav a").height(),
			finalNavH = navH - inneNavH,
			finalNavH = finalNavH / 2;

		$("header nav.default a").css({
			'paddingTop': finalNavH,
			'paddingBottom': finalNavH,
			'paddingLeft': 50,
			'paddingRight': 50
		});

		$("header nav.default a.oque").css("top", navH);
		$("header nav.default a.clientes").css("top", navH * 2);
		$("header nav.default a.contato").css("top", navH * 3);
		$("header nav.default a.blog").css("top", navH * 4);
	}
}
