var busy = false;
var selectionMade = false;
var selectedItem = null;
var subnav = null;
var selectedSub = null;
var currentHash = "";

var hashInterval = setInterval( function(){
  if( window.location.hash != currentHash && !busy ) {
    
    processHash();
    loadCurrentPage();
  }
}, 500 );

$(document).ready(function(){

  processHash();

  if( !currentPage ) {
    currentPage = "home";
  }

  $(".toggle_button").click(function(){
    return false;
  });

  $("#menu-title").each(function(i,obj){
    //$(obj).removeClass( "active" );
    //selectedItem = obj;
  });

  var nav = $("#nav").get(0);
  var container = $("#container").get(0);
  $(nav).hover(function(){
    if( !mobile ) {
    $("ul", nav).stop(true, false).animate({ height: 47, paddingTop: 21 }, 200, 'swing', function(){
      
    });
    
    $("#logo").stop(true,false).animate({ height: 217 }, 200, 'swing', function(){

    });
    }
  },function(){
    if( !mobile ) {
    $("ul", nav).stop(true, false).animate({ height: 0, paddingTop: 3 }, 200, 'swing', function(){
      
    });
    
    $("#logo").stop(true,false).animate({ height: 217 }, 200, 'swing', function(){

    });
    }
  });

  $(".navmenu").each(function(i,obj){
    $(obj).click(function(){
      if( currentPage != obj.id || currentData != "" ) {
        currentPage = obj.id;
        currentData = "";
        loadCurrentPage();
      }
      return false;
    });
  });

  loadCurrentPage();

});

function processHash() {
  var hash = window.location.hash;
  if( hash ) {
    hash = hash.substr( 1, hash.length );
    var split = hash.split( "?" );
    currentPage = split[0];
    currentData = split[1];
  }
}
var currentRequest = null;
function loadCurrentPage() {
  pageImages = [];
  pageSources = [];
  
  busy = true;
  $("#container").html( "<div style=\"text-align: center; width: 47px; margin: 0 auto; padding: 5px 5px 3px 5px; background-color: #FFFFFF; border-radius: 5px; -moz-border-radius: 5px;\"><img src=\"images/fbloading.gif\" /></div>" );
  $(document).scrollTop(0);
  currentHash = "#" + currentPage + "?" + currentData;
  if( currentPage == "home" ) {
    $("#logo > #home").css({position:"static"});
  } else {
    $("#logo > #home").css({position:"fixed"});
  }
  window.location.hash = currentHash;
  if( currentRequest ) {
    currentRequest.abort();
    currentRequest = null;
  }
  currentRequest = $.ajax({
    type: 'POST',
    url: currentPage + ".php",
    data: currentData,
    error: function( a, b, c ) {
      //alert( c );
    },
    success: function( data, status, request ){

      $(".navmenu").each(function(i,obj){
        if( currentPage == obj.id ) {
          $(obj).removeClass("standard_btn");
          $(obj).addClass("standard_btn_selected");
        } else {
          $(obj).removeClass("standard_btn_selected");
          $(obj).addClass("standard_btn");
        }
      });

      currentRequest = null;
      $("#container").css("display","none");
      $("#container").html(data);
      /*if( currentPage == "home" && !mobile ) {
        var random = Math.floor(1+(Math.random()*4));
        $("html").css("background","#EDEDED url(images/" + currentPage + "topbg" + random + ".jpg) no-repeat top center fixed");
        $("#header #nav .holder").css("background","#EDEDED url(images/" + currentPage + "topbg" + random + ".jpg) no-repeat top center fixed");
      } else {*/
        $("html").css("background","#EDEDED url(images/intertrendbg.jpg) no-repeat top center fixed");
        $("#header #nav .holder").css("background","#EDEDED url(images/intertrendbg.jpg) no-repeat top center fixed");        
      //}
      hideAllObjects();
      $("#container a[rel=lightbox]").each(function(i,obj){
        $(obj).lightBox();
      });
      $(document).load(function(){
        
      });
      busy = false;
      $(".return_top").click(function(){
        $('html,body').animate({ scrollTop: 0 }, 800, 'swing', function(){

        });
        return false;
      });
      $(".page_link").click(function(){
        var obj = $(this).get(0);
        if( obj.id ) {
          changeCurrentPage( obj.id, obj.target );
        }
        return false;
      });
      $(".scroll_link").click(function(){
        var obj = $(this).get(0);
        var target = $(obj).attr("target");
        var offset = $("#" + target).parent().offset();
        
        var top = offset.top;
        //$(document).scrollTop(offset - 100);
        
        $('html,body').animate({ scrollTop: top - 100 }, 800, 'swing', function(){

        });
        return false;
      });
      processSearch();
      $("#container").css("display","block");

      initializeForm();

      showSeenObjects();

      $(".slideholder").each(function(i,obj){
        initializeSlideShow( obj );
      });

      $(".project_thumb > .project_info_open").each(function(i,obj){
        $(obj).css("margin-top",(216-$(obj).outerHeight())+"px");
      });

      $(".project_thumb_alt > .project_info_open").each(function(i,obj){
        $(obj).css("margin-top",(148-$(obj).outerHeight())+"px");
      });

      $("#container .project_thumb").each(function(i,obj){
        var info = $(".project_info",obj).get(0);
        $(".project_href",obj).hover(function(){
          $(info).stop(true, false).animate({ marginTop: 216-$(info).outerHeight() }, 200, 'swing', function(){

          });
        },function(){
          $(info).stop(true, false).animate({ marginTop: 216 }, 200, 'swing', function(){

          });
        });
      });

      $("#container .project_thumb_alt").each(function(i,obj){
        var info = $(".project_info",obj).get(0);
        $(".project_href",obj).hover(function(){
          $(info).stop(true, false).animate({ marginTop: 148-$(info).outerHeight() }, 200, 'swing', function(){

          });
        },function(){
          $(info).stop(true, false).animate({ marginTop: 144 }, 200, 'swing', function(){

          });
        });
      });
    },
    dataType: 'html'
  });
}

function initializeSlideShow( show ) {
  var slideImages = [];
  var currentSlide = 0;
  var timerCount = 0;
  $(".slideimage",show).each(function(i,obj){
    slideImages.push( obj );
  });
  animateSlides( slideImages[currentSlide], null );
  var timerInterval = setInterval( function(){
    timerCount++;
    if( timerCount == 5 ) {
      var oldSlide = currentSlide;
      currentSlide++;
      if( currentSlide >= slideImages.length ) {
        currentSlide = 0;
      }
      animateSlides( slideImages[currentSlide], slideImages[oldSlide] );
      timerCount = 0;
    }
  },1000);
  $(".slidenext",show).click(function(){
    var oldSlide = currentSlide;
    currentSlide++;
    if( currentSlide >= slideImages.length ) {
      currentSlide = 0;
    }
    animateSlides( slideImages[currentSlide], slideImages[oldSlide] );
    timerCount = 0;
    return false;
  });
  $(".slideprev",show).click(function(){
    var oldSlide = currentSlide;
    currentSlide--;
    if( currentSlide < 0 ) {
      currentSlide = slideImages.length - 1;
    }
    animateSlides( slideImages[currentSlide], slideImages[oldSlide] );
    timerCount = 0;
    return false;
  });
}

function animateSlides( slide1, slide2 ) {
  if( slide1 ) {
    $(slide1).css( "display", "block" );
    $(slide1).css( "opacity", "0" );
    $(slide1).stop(true, false).animate({ opacity: 1 }, 500, 'swing', function(){

    });
  }
  if( slide2 ) {
    $(slide2).stop(true,false).animate({ opacity:0 }, 500, 'swing', function(){
      $(slide2).css( "display", "none" );
    });
  }
}

function initializeForm() {
  var form = $("#contact_form").get(0);
  if( form ) {
    var submitter = $("#form_submitter").get(0);
    var content = $("#form_content").get(0);
    $(submitter).click(function(){
      $("#form_error").css("display","hidden");
      var cdata = "";
      var name = escape( $("input[name=contact_name]",form).val() );
      var email = escape( $("input[name=contact_email]",form).val() );
      var company = escape( $("input[name=contact_company]",form).val() );
      var phone = escape( $("input[name=contact_phone]",form).val() );
      var message = escape( $("textarea[name=contact_message]",form).val() );

      if( !name || !email || !company || !phone || !message ) {
        $("#form_error").css("display","block");
        return false;
      }

      var height = $(content).outerHeight();
      $(content).css("height", height + "px");
      $(content).html("Sending data, please wait...");

      cdata = "contact_form=1&contact_name=" + name + "&contact_email=" + email + "&contact_company=" + company + "&contact_phone=" + phone + "&contact_message=" + message;

      $.ajax({
        type: 'POST',
        url: "index.php",
        data: cdata,
        success: function( data, status, request ){
          $(content).html( "Your inquiry has been received.  Thank you!" );
        }
      });

      return false;
    });
  }
}

$(window).scroll(function(){
  showSeenObjects();
});

var elementTypes = [".loadelement"]
var elementClasses = ["loadelement"];
var pageImages = [];
var pageSources = [];
function hideAllObjects() {
  $.each(elementTypes,function(i,val) {
    $(val).each(function(j,obj){
      if( obj.tagName == "IMG" ) {
        pageImages.push( obj );
        pageSources.push( obj.src );
        $(obj).removeAttr( "src" );
      }
      $(obj).css( "visibility", "hidden" );
    });
  });
}

function showSeenObjects() {
  $.each(elementTypes,function(i,val){
    $(val).each(function(j,obj){
      if( $(obj).css("visibility") == "hidden" ) {
        var elTop = $(obj).offset().top - $(window).scrollTop();
        var elHeight = $(obj).height();
        if (elTop + elHeight > 40 && elTop < $(window).height()) {
          if( obj.tagName == "IMG" ) {
            $(obj).attr( "src", pageSources[pageImages.indexOf(obj)] );
            $(obj).load(function(){
              showObject(obj);
            });
          } else {
            showObject(obj);
          }
        }
      }
    });
  });
}

function showObject( obj ) {
  $(obj).css("visibility", "visible");
  $(obj).animate({
    opacity: 0
  }, 10, function() {

  });
  $(obj).stop(true, true).animate({
    opacity: 1
  }, 1000, function() {
    // Animation complete.
  });
  var totalTypes = elementClasses.length;
  for( var i = 0; i < totalTypes; i++ ) {
    if( $(obj).hasClass(elementClasses[i]) ) {
      $(obj).removeClass(elementClasses[i]);
    }
  }
}

var searchajax = null;
var autoCompletions = [];
var currentAuto = null;
function processSearch() {
  var input = $("input[name=search_query]").get(0);
  $(input).keyup(function(event){
    if( event.which == "38" || event.which == "40" ) {
      processAutoKey( event.which );
      return;
    }
    currentAuto = null;
    autoCompletions = [];
    if( searchajax != null ) {
      searchajax.abort();
    }
    $("#autocomplete").html("");
    searchajax = $.ajax({
      type: 'POST',
      url: "autocomplete.php",
      data: "query=" + input.value,
      error: function( a, b, c ) {
        //alert( "Request to autocomplete.php failed. " + "autocomplete.php?query=" + input.value );
      },
      success: function( data, status, request ){
        var total = data.data.length;
        if( total > 0 ) {
          $("#autocomplete").css("display","block");
        } else {
          $("#autocomplete").css("display","none");
        }
        for( i = 0; i < total; i++ ) {
          $("#autocomplete").append( "<a href=\"#\" class=\"autolink\">" + data.data[i] + "</a>" );
        }
        processAutoComplete();
      },
      dataType: 'json'
    });
  });
  var submitsearch = $("#content .submit_search").get(0);
  $(submitsearch).click(function(){

    processInputForm();
    return false;
  });
  $("#content input[name=search_query]").keydown(function(event){
    if( event.which == "13" ) {
      if( currentAuto ) {
        $("input[name=search_query]").val($(currentAuto).text());
      }
      processInputForm();
    }
  });
}

function processAutoComplete() {
  $(".autolink").each(function(i,obj){
    $(obj).click(function(){
      $("input[name=search_query]").val($(obj).text());
      processInputForm();
      return false;
    });
  });
}

function processAutoKey( key ) {
  if( currentAuto ) {
    $(currentAuto).removeClass("autolink_selected");
  }
  
  if( key == "38" ) {
    if( !currentAuto ) {
      currentAuto = $(".autolink").get(0);
    } else {
      var prev = null;
      var selected = false;
      $(".autolink").each(function(i,obj){
        if( !selected ) {
          if( obj == currentAuto ) {
            currentAuto = prev;
            selected = true;
          }
          prev = obj;
        }
      });
    }
  } else {
    if( !currentAuto ) {
      currentAuto = $(".autolink").get(0);
    } else {
      var found = false;
      var selected = false;
      $(".autolink").each(function(i,obj){
        if( !selected ) {
          if( found ) {
            currentAuto = obj;
            selected = true;
          }
          if( obj == currentAuto ) {
            found = true;
          }
        }
      });
    }
  }

  if( currentAuto ) {
    $(currentAuto).addClass("autolink_selected");
  }
}

function processInputForm() {
  var input = $("input[name=search_query]").val();
  if( input ) {
    if( selectProperInput( input, ["projects","recent","recent work","work","project"] ) ) {
      changeCurrentPage( "projects", "" );
    } else if( selectProperInput( input, ["services","creative","strategy","account"] ) ) {
      changeCurrentPage( "services", "" );
    } else if( selectProperInput( input, ["news","articles"] ) ) {
      changeCurrentPage( "news", "" );
    } else if( selectProperInput( input, ["contact","location","phone","email","e-mail","map","contact form"] ) ) {
      changeCurrentPage( "contact", "" );
    } else if( selectProperInput( input, ["about","clients","brands","press","awards","about us","company"] ) ) {
      changeCurrentPage( "clients", "" );
    } else {
      changeCurrentPage( "search", "query=" + input );
    }
  }
}

function selectProperInput( input, cases ) {
  var total = cases.length;
  for( var i = 0; i < total; i++ ) {
    var ilen = input.length;
    var clen = cases[i].length;
    if( ilen == clen ) {
      var matches = 0;
      for( var j = 0; j < ilen; j++ ) {
        if( cases[i].indexOf( input.charAt(j) ) >= 0 ) {
          matches++;
        }
      }
      if( matches == ilen ) {
        return true;
      }
    }
  }
  return false;
}

function changeCurrentPage( page, data ) {
  currentPage = page;
  currentData = data;
  loadCurrentPage();
  return false;
}
