/* Authors: Jake and Ian C */

var HOME_HTML = ""; // home page html
var SEARCH_QUERY = ""; // track search query as ba-hashchange removes ? on hash

$(document).ready(function() {
  HOME_HTML = $('#main').html();
  initNavBar();
  selectNavItem("home");
  initBanners();
  initNews();
  initPage();
  resizeLayout();
});


// detect window resize
$(window).resize(function() {
  clearTimeout(this.id);
  this.id = setTimeout(resizeLayout, 150);
});


// detect enter on searchField to submit search
$('#searchField').bind('keypress', function(e) {
  var code = (e.keyCode ? e.keyCode : e.which);
  if(code == 13) { //Enter keycode
    loadPage({page: "/search/site", query: $("#searchField").val(), title:"Search Site"});
  }
});


function asteroidsKeyup(e) {
  if(e.keyCode == 27) {
    //alert("escaped...");
    location.reload();
    $(document).unbind("keyup", asteroidsKeyup);
  } 
}



// use jquery hashchange plugin to support IE7
// see: http://benalman.com/projects/jquery-hashchange-plugin/
$(function() {
  $(window).hashchange( function() {
    initPage();
    trackAnalytics();
  });
});


// recalculate the layout for best fit on smaller browsers
function resizeLayout()
{
  // get layout dimensions
  var height = $(window).height();
  var main_offset = $('#main').offset();
  var main_top_pos = main_offset.top;
  var main_bottom =  main_top_pos + $('#main').height();
  //alert(main_bottom.toString());

  // layout settings with min and max dimensions
  var minmaxy_body = {min:963, max:1165};
  var minmaxy_main = {min:-200, max:0};
  if ($('body').hasClass('inside')) { 
    minmaxy_main = {min:-50, max:0}; // inside pages
  }
  var minmaxy_heading = {min:82, max:116};
  var minmaxy_one = {min:94, max:221};
  var minmaxy_two = {min:94, max:184};
  var minmaxy_three = {min:94, max:135};


  // scale dimensions
  var percentage = (height - minmaxy_body.min) / (minmaxy_body.max - minmaxy_body.min);
  if (percentage < 0) { percentage = 0; }
  if (percentage > 1) { percentage = 1; } 
  //alert((percentage*100).toString() + "%");

  var new_top_pos = minmaxy_main.min + ((minmaxy_main.max - minmaxy_main.min) * percentage);
  $('#main').css('top', new_top_pos.toString() + "px");
  $('#section-heading').css('top', (minmaxy_heading.min + ((minmaxy_heading.max - minmaxy_heading.min) * percentage)).toString() + "px");
  $('#splash div#one').css('top', (minmaxy_one.min + ((minmaxy_one.max - minmaxy_one.min) * percentage)).toString() + "px");
  $('#splash div#two').css('top', (minmaxy_two.min + ((minmaxy_two.max - minmaxy_two.min) * percentage)).toString() + "px");
  $('#splash div#three').css('top', (minmaxy_three.min + ((minmaxy_three.max - minmaxy_three.min) * percentage)).toString() + "px");

  // adjust footer relative to main
  //alert(new_top_pos.toString());
  $('footer').css('margin-top', new_top_pos.toString() + "px");
}


// initialise new page
function initPage()
{
  var hash = document.location.hash;	
  var myRegexp = /#!(\/.*)$/g;
  var match = myRegexp.exec(hash);
  if (match != null) {
    //alert('loading page... ' + match[1]);
    loadPage({page: match[1].split("?")[0], title: "Insight4 | Enterprise Application Specialists"});
  }
  // index page
  if (document.location.hash == "") {
    loadPage({page: "/", title: "Insight4 | Enterprise Application Specialists"});
  }
}


// load home page
function loadHomePage()
{
  $("#main").html(HOME_HTML);
  initNews();
  selectNavItem("home");
  document.location.hash = '';
  document.title = "Insight4 | Enterprise Application Specialists"
  $("#section-heading").hide();
  $("body").removeClass("inside");
  $("#one").fadeIn();
  $("#two").fadeIn();
  $("#three").fadeIn();
}


// select a nav item
function selectNavItem(section)
{
  // remove selected classes
  $("#topnav-home").removeClass("current");
  $("#topnav-company").removeClass("current");
  $("#topnav-services").removeClass("current");
  $("#topnav-industries").removeClass("current");
  $("#topnav-careers").removeClass("current");
  $("#topnav-contact").removeClass("current");
  
  // select current nav bar item
  $("#topnav-"+section).addClass("current");

}


// select a menu item
function selectMenuItem(section, pagename)
{ 
  // select current menu item
  $("#menu-"+section+"-"+pagename).addClass("current");
}


// track ajax page loads with google analytics
// http://davidwalsh.name/ajax-analytics
function trackAnalytics()
{
  // "_trackEvent" is the pageview event, 
  var page = document.location.hash;
  _gaq.push(['_trackPageview', page]);
}


// load page handler
function loadPage(opts) {

  // now handled by the anchor div, as resetting the hash interfered with the history
  //document.location.hash = '';
  //$("html").scrollTop(); 

  // hide asteroids if it was shown
  $('#asteroids-intro').hide();

  if (opts.page == "/") {

      // index page
      loadHomePage();
      resizeLayout();
      trackAnalytics();

  } else {

      // set search query
      if (opts.query != undefined) {
        SEARCH_QUERY = opts.query;
      }

      document.location.hash = '!' + opts.page; // make hashbang
      document.title = opts.title + " | Insight4";

      // load content via ajax call
      $('#main').load('/?_escaped_fragment_=' + opts.page, function() {

        var parts = document.location.hash.split("/");
        var section = parts[1].split("?")[0];
        var pagename = parts[2].split("?")[0];

        // use inner page, hide index slides
        $("body").addClass("inside");
        $("#one").hide();
        $("#two").hide();
        $("#three").hide();

        // fade in section heading
        $('#section-heading').html(section).fadeIn();

        // select top nav item
        selectNavItem(section);

        // select menu item
        selectMenuItem(section, pagename);

        // resize layout
        resizeLayout();

        // track analytics
        trackAnalytics();
      });
  } 
  return true;
}

function isValidEmailAddress(email)
{
	var filter = /^([\w-\.+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
	return filter.test(email);
}

function submitNewsletterEmail()
{
	if (!isValidEmailAddress($('#emailField').val())) {
        	alert("Please enter a valid email address");
		return false;
	}

	// valid
	return true;     
}

function initBanners()
{
    //Set the speeds for the various banners/sliders
    var bannerSpeed = 12000;
    
    //Start the sliders and set their speed using the values provided
    var bannerInterval = setInterval("slideSwitch()", bannerSpeed);
}


function initNews()
{
  //Hides the unwated div in the main aside
  $('#success').hide();
  $('a#show-news').css('color', '#fff');

  //Hides and shows the news and success stories
  $('#show-stories').click(function () {
    $('#news').hide();
    $('a#show-news').css('color', '#484848');
    $('a#show-stories').css('color', '#fff');
    $('#success').show();
  });

  $('#show-news').click(function () {
    $('#success').hide();
    $('a#show-stories').css('color', '#484848');
    $('a#show-news').css('color', '#fff');
    $('#news').show();
  });
}


function initNavBar()
{
//Navigation dropdown
    $('ul.topnav li a').mouseover(function() { //When trigger is clicked...
    	 

    		//Following events are applied to the subnav itself (moving subnav up and down)
    		$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on hover

    		$(this).parent().hover(function() {
    		}, function(){
    			   $(this).parent().find('ul.subnav').slideUp('slow').stop(true,true);
    		});

    		//Following events are applied to the trigger (Hover events for the trigger)
    		}).hover(function() {
    			$(this).addClass("subhover"); //On hover over, add class "subhover"
    		}, function(){	//On Hover Out
    			$(this).removeClass("subhover"); //On hover out, remove class "subhover"
    	});
}




        
/*
 *  Function which changes the slides in the slideshow on the front page
 */

function slideSwitch() {
    
    //Get the currently active image
    var $active_img = $('#slider div.active');
    var $active_txt = $('#splash div.active');
    
    //check to see if we are at the last image
    if(!$active_img.next('div').length){
        //if we are at the last image, get the first img element in the slideshow to display next
        $next_img = $('#slider').children('div:first'); 
        $next_txt = $('#splash').children('div:first');
    }
    else{
        //else just next the next image element
        $next_img = $active_img.next('div');
        $next_txt = $active_txt.next('div');   
    }
    
    //Give the active elements the last-active class to give them a lower z-index than the next elements to be displayed
    $active_img.addClass('last-active').animate({opacity: 0.0}, 750);
    $active_txt.addClass('last-active').animate({opacity: 0.0}, 750);
    
    //Animate the opacity of the next image to be displayed and give it the '.active' class to bring it to the front
    $next_img.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 750, function() {
      $active_img.removeClass('active last-active');
    });
    
   $next_txt.css({opacity: 0.0}).addClass('active').animate({opacity: 1.0}, 750, function() {
        $active_txt.removeClass('active last-active');
    });
};
