// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var timeBefore = null; // javascript timestamp. used to keep time stamp before current request
var timeTaken = 4000; // time in miliseconds taken by recent longest time taken request

var ua = navigator.userAgent;
var hostAndProtocol = location.protocol+"//"+location.host;

var isiPhoneOriPad = /iPad/i.test(ua) || /iPhone OS/i.test(ua);


var target;
var pathname;
$(document).ready(function(){
  pathname = window.location.pathname;
  var img = 0;
  var img_width = 0;
  var new_height;
    
  $('#navigation').hoverIntent(function(){
    $('#sub_navigation_1').slideDown(500);
  },function(){
    $('#sub_navigation_1').slideUp(500);
  });
  
  $('#sub_navigation_1 li a, #navigation_1 li a, #site_map li a, #title_right a, #navigation_2 a, #about_us, #about_us, #jobs, #home_carousel a').click(function(){
    if($(this).parent().hasClass('futurist') == false && $(this).hasClass('job_anchor') == false ){
      load_page($(this));
    	return false;
    } else if ($(this).parent().hasClass('futurist') == true ){
			
		} else {
    	return false;
		}
  });

  $('#close,a#logo').click(function(){
    $('#content').css('border-bottom','none');
    $('#content').animate({height: '0px'},500);
    $("title").text("Branding, Design and Online Solutions - Freerange Future")
    $('#navigation_1 .case_studies img').attr('src','/images/nav_arrow.png');
    $('#navigation_1 .services img').attr('src','/images/nav_arrow.png');
    $('#navigation_1 .projects img').attr('src','/images/nav_arrow.png');
    $('#navigation_1 .methodology img').attr('src','/images/nav_arrow.png');
  });
  
  $('#home_carousel').anythingSlider({
    width          : 483,
    height         : 310,
    delay          : 5000,
    toggleControls : false
  });
  init_project();
  init_newsletter();
  
  
  $("#loaded").bind("ajaxSend", function(){
    $('#page_in_progress').height($(window).height());
    $('#page_in_progress').width($(window).width());
    $('#page_in_progress').addClass('show');
    timeBefore = (new Date().getTime()); // current time stamp for calculating time takens
    var animation_delay = 20000;
    if( timeTaken > 5000 )
      animation_delay = timeTaken * 5;
    else
      animation_delay = timeTaken * 2;
    
    $("#loading").show()
    $("#loading").animate({width: "100%"}, animation_delay, function(){
      $(this).width("0");
      
    });
    
    
    
    
  }).bind("ajaxComplete", function(){
    var timeAfter = (new Date().getTime());
    var currentReqTimeTaken = (timeAfter - timeBefore ) ;
    //update timetaken only if current request took more time than previous longest request or if timetake == 6000. this is initial value
    if(timeTaken < currentReqTimeTaken || timeTaken == 6000){ 
      timeTaken = currentReqTimeTaken ; // time difference in milisecs
    }
    
    $("#loading").stop().animate({width:"100%"}, 500, function(){
      $(this).width("0");
      $("#loaded").show();
      $('#page_in_progress').removeClass('show');
    });    
    
    
  });
  
  
  $.ajaxHistory.addCallback(function(newHash){
        load_page2(newHash);
   });
    $.ajaxHistory.init(function(hash){     
      load_page2(hash);
    }, { baseURL: "/home", defaultTitle:$.trim($("title").text()) });
  
  init_service_rollovers();
  if( $("#content_holder").html().match(/[a-z,A-Z]+/) != null ){
    new_height = $('#ajax_content').height();
    $('#content').animate({height: new_height+80},500,function(){
      $('body').scrollTo( '#navigation_1', 500 );
    });
  }
  
});

function load_page(link){
  url = link.attr('href');
  target = url + ' #ajax_content';
  //$.history.load(target);
  if(link.attr('href') != "javascript:;"){
    $.ajaxHistory.addHistory(url.replace("../../../../..",""));
    load_page2(target);
  }  
}

function load_page2(url){

  //Google Tracking 
  try{
    pageTracker._trackPageview( url );
  }catch(e){}
  target = url +' #ajax_content';
  $('#navigation_1 ul').slideUp(500);
  $('#content').animate({height: '0px'},500,function(){
    $('#content').css('border-bottom','#C0BFBE 1px solid');
    $('#content_holder').load(url,function(){
      
      if($('.tags_page').length > 0){
        init_tags_page();
      }
      if($('#project_info').length > 0){
        init_project();
      }
		  if($('#carousel').length > 0){
		    if($('#project_info').height() < $('#carousel').height()){
		      $('#project_info').css('height',$('#carousel').height());
		    }
		  }

	  if($('.methodology_page').length > 0){
	    $('#navigation_1 .methodology img').attr('src','/images/nav_arrow_ro.png');
	  } else {
	    $('#navigation_1 .methodology img').attr('src','/images/nav_arrow.png');
		}
	  if($('.project.case_study').length > 0){
	    $('#navigation_1 .case_studies img').attr('src','/images/nav_arrow_ro.png');
	  } else {
	    $('#navigation_1 .case_studies img').attr('src','/images/nav_arrow.png');
		}
	  if($('.servies_page').length > 0){
	    $('#navigation_1 .services img').attr('src','/images/nav_arrow_ro.png');
	  } else {
	    $('#navigation_1 .services img').attr('src','/images/nav_arrow.png');
		}
	  if($('.project').length > 0 && $('.project.case_study').length == 0){
	    $('#navigation_1 .projects img').attr('src','/images/nav_arrow_ro.png');
	  } else {
	    $('#navigation_1 .projects img').attr('src','/images/nav_arrow.png');
		}
      new_height = $('#ajax_content').height();
      $('#content').animate({height: new_height+80},500,function(){
        if(isiPhoneOriPad){
          //$('#sub_navigation_1').slideUp(500);
          
          $('body').scrollTo("+=400px");   
        }else{
          $('body').scrollTo( '#navigation_1', 500 , { onAfter:function(){
               $('body').scrollTo("-=9px");                                 
            }
          })
        }
        
      });
      
      init_internal_page_ajax();
      
      if($("#ajax_content").length > 0 && $("#ajax_content").attr('rel') != "")
        $("title").text($("#ajax_content").attr('rel') + " - Freerange Future");
      else
         $("title").text("Freerange Future");
    });
  });
  
  
  
}

function init_internal_page_ajax(){
  $("#ajax_content a.ajax").click(function(){
    load_page($(this));
    return false;
  });
}

function init_tags_page(){
  $('.tags_page a').click(function(){
    load_page($(this));
    return false;
  });
}
var banner_counter_int
function sign_up_fade_counter(){
  var banner_counter = 0;
  banner_counter_int = setInterval(function() {
      banner_counter++;
      if (banner_counter > 10) {
          banner_counter = 0;
          $('.anythingSlider').fadeIn();
          $('#newsletter_sign_up_form').fadeOut();
          clearInterval(banner_counter_int);
    }
  },
  1000);
  $('#newsletter_sign_up_form').mouseenter(function(){
    clearInterval(banner_counter_int);
  });
  $('#newsletter_sign_up_form').mouseleave(function(){
    banner_counter_int = setInterval(function() {
        banner_counter++;
        if (banner_counter > 10) {
            banner_counter = 0;
            $('.anythingSlider').fadeIn();
            $('#newsletter_sign_up_form').fadeOut();
            clearInterval(banner_counter_int);
        }
    },
    1000);
  });
}

function init_newsletter(){
  $('#newsletter_sign_up').click(function(){
    clearInterval(banner_counter_int);
    $('.anythingSlider').fadeOut();
    $('#newsletter_sign_up_form').fadeIn();
    sign_up_fade_counter();
  });
  $('#newsletter_sign_up_form a').click(function(){
    $('.anythingSlider').fadeIn();
    $('#newsletter_sign_up_form').fadeOut();
  });
  
  $(".defaultText").focus(function(src){
      if ($(this).val() == $(this)[0].title){
          $(this).removeClass("defaultTextActive");
          $(this).val("");
      }
  });
  $(".defaultText").blur(function(){
      if ($(this).val() == ""){
          $(this).addClass("defaultTextActive");
          $(this).val($(this)[0].title);
      }
  });
  $(".defaultText").blur();
  $('#newsletter_submit').click(function(){
    $('#newsletter_signup').find('.defaultText').each(function(){
      if($(this).val() == $(this)[0].title){
        $(this).val('');
      }
    });
  });
}

function init_project(){
  img = 0;
  img_width = 0;
  $('#carousel_inner').find('div').each(function(){
    img++;
    $(this).addClass('image_'+img);
    $(this).css('width','725px');
  });
  $('#carousel_inner').css('width',img*725+'px');
  
  var loadingInterval = setInterval(function() {
    if (img >= $('#carousel_inner').find('img').length) {
        clearInterval($(this));
      }
    },
  100);
  
  init_carousel();

  $('.tag_list a').click(function(){
    load_page($(this));
    return false;
  });
  if($('.case_study').length > 0){
    if($('#project_info').height() < $('#case_study_images').height()){
      $('#project_info').css('height',$('#case_study_images').height()-40);
    }
  }
  if($('#carousel').length > 0){
    if($('#project_info').height() < $('#carousel').height()){
      $('#project_info').css('height',$('#carousel').height());
    }
  }
}

function init_carousel(){
  $('#carousel').prepend('<a href="javascript:;" id="car_left">left</a>');
  $('#carousel').append('<a href="javascript:;" id="car_right">right</a>');
  $('#carousel').append('<div id="car_status"><span id="current_status"></span><span id="total_status"></span></div>');
  $('#current_status').text('1');
  $('#total_status').text(img);
  var img_width = $('#carousel').find('img:first').width();
  var current_position = 0;
  $('#car_left').click(function(){
		if(current_position > 0){
			current_position --;
			$('#current_status').text(current_position+1);
  		$('#carousel_inner').animate({'margin-left': '+=725px'},500);
			$('current_image').removeClass('current_image');
			$('image_'+current_position).addClass('current_image');
			if(current_position == 0){
				$(this).addClass('disabled');
			} else {
				$(this).removeClass('disabled');
			}
			$('#car_right').removeClass('disabled');
		}
  });
	$('#car_left').addClass('disabled');
  $('#car_right').click(function(){
		if(current_position < img-1){
			current_position ++;
			$('#current_status').text(current_position+1);
  		$('#carousel_inner').animate({'margin-left': '-=725px'},500);
			if(current_position == img-1){
				$(this).addClass('disabled');
			}
			$('#car_left').removeClass('disabled');
		}
  });
}


function init_service_rollovers(){
  $('#navigation_2').find('.box').mouseenter(function(){
    $('#rollover').fadeIn('slow');
    if($(this).hasClass('gluttonberg') == true){
      $('#rollover').find('div').css('display','none');
      $('#rollover #gb_rollover').css('display','block');
      $('#rollover').css('left','275px');
      $('#rollover').css('background','url(../images/service_rollover_left.png) left top no-repeat');
    }
    if($(this).hasClass('brand_bundle') == true){
      $('#rollover').find('div').css('display','none');
      $('#rollover #tenk_rollover').css('display','block');
      $('#rollover').css('left','535px');
      $('#rollover').css('background','url(../images/service_rollover_left.png) left top no-repeat');
    }
    if($(this).hasClass('futurist') == true){
      $('#rollover').find('div').css('display','none');
      $('#rollover #blog_rollover').css('display','block');
      $('#rollover').css('left','260px');
      $('#rollover').css('background','url(../images/service_rollover_right.png) right top no-repeat');
    }
    if($(this).hasClass('tech_tonic') == true){
      $('#rollover').find('div').css('display','none');
      $('#rollover #tt_rollover').css('display','block');
      $('#rollover').css('left','530px');
      $('#rollover').css('background','url(../images/service_rollover_right.png) right top no-repeat');
    }
  });
  $('#navigation_2').find('div').mouseleave(function(){
    $('#rollover').hide();
  });
}
