// Handles all the AJAX loading and general housekeeping.
var Loader = {
  init: function() {
    
    this.hostAndProtocol = location.protocol+"//"+location.host;
    //this.connectionSpeed = 300; // kbps kilo bits per sec. Initialized with normal dsl speed. Actual connection speed will be calculated on ajax request
    this.timeBefore; // javascript timestamp. used to keep time stamp before current request
		this.timeTaken = 6000; // time in miliseconds taken by recent longest time taken request
		this.imagePreloader = $('<div></div>').css({width:"0px", height:"0px", position:"absolute", top:"50%", left:"50%", overflow:"hidden"});
    $("body").append(this.imagePreloader);
    
    this.container = $("#container");
    this.containerOverlay = $('<div id="containerOverlay">').css({width:Math.max($("body").width(), $("#container").width())+"px"});
    this.container.before(this.containerOverlay);
    
    // Set up navigation
    flashXMLfromHTML({
      swf: "/flash/menu.swf",
      targetElements: $("#main-nav, #sub-nav"),
      id: "flashMenuReplace",
      wrap: true,
      replace:[
        { match:new RegExp('href="'+this.hostAndProtocol, "g"), replacement:'href="' }
      ]
    });
    
    this.loaderDial = $('<div id="loader-dial"></div>');
    this.loaderDialArrowStart = "397px";
    this.loaderDialArrowEnd = "552px";
    this.loaderDialArrow = $('<img id="loader-dial-arrow" src="/images/layout/loader-arrow.png" />').css({left: this.loaderDialArrowStart});
    if($.browser.msie && parseInt($.browser.version) < 7) DD_belatedPNG.fix('#loader-dial-bg, #loader-dial-arrow');
    this.loaderDial.append(this.loaderDialArrow);
    this.loaderDial.fadeOut(0);
    this.containerOverlay.append(this.loaderDial);
    
    //define a recursive function setup to make the loader arrow bounce at the end
    this.loopingLoaderArrow = function(duration){
      Loader.loaderDialArrow.animate({left:Loader.loaderDialArrowEnd}, duration, function(){
        $(this).animate({left:(parseInt(Loader.loaderDialArrowEnd)-10)+"px"}, 500, function(){
          Loader.loopingLoaderArrow(500);
        });
      });
    };
    
    //add the callback to call if the hash changes. callback will get called even if the hash is changed to an empty string
    $.ajaxHistory.addCallback(function(newHash, isBase){
      Loader.isBase = isBase;
      Loader.get(newHash);
    });
    
    //init history with the callback and baseURL
    var foundHash = $.ajaxHistory.init(
      function(hash){ //this callback will only get called if the hash is not empty
        Loader.containerOverlay.css({display:"block", opacity:"1"});//hide whatevers visible straight away
        Loader.get(hash);
      },
      { baseURL: "/index", titlePrefix:"Matilda Bay Brewing Company", defaultTitle:"Matilda Bay Brewing Company" }
    );
    
    //if the initial page has an empty hash, discover where we are (will almost always be the home page)
    if(!foundHash){
      Sections.discover();
    };
    
  },
  
  get: function(url) {
    url = url.replace(/\/$/, "/index"); //replace trailing slashes with call to index
    this.shortened = false;
    if(url.indexOf('?shortened=true') > -1) this.shortened = true;
    url = url.replace('?shortened=true', '');
    
    if(this.currentURL == url) return; //dont bother if for some reason we are requesting the same url
    this.currentURL = url;
    this.fadeCompleted = false;
    this.requestCompleted = false;
    
    if (this.pendingRequest) this.pendingRequest.abort();
    
    if(this.shortened){
      $("#content").animate({opacity:"0"}, 1000, "linear", this.fadeOutComplete);
      // Remove the paginator
      $("#hand-navigation").remove();
    } else {
      //fade up the overlay
      this.containerOverlay.stop().css({width:Math.max($("body").width(), $("#container").width())+"px"}); //make sure the overlay is big enough to cover everything
      if(this.containerOverlay.css('display') == 'none') this.containerOverlay.css({display:"block", opacity:"0"});
      this.containerOverlay.animate({opacity: "1"}, 1000, "linear", this.fadeOutComplete);
    }
    
    
    Loader.loaderDialArrow.stop().css({left:Loader.loaderDialArrowStart});
    //start the loader arrow on its path
		
		// calculate animation delay based on highest time taken by recent requests.
			var animation_delay = 20000;
			if( Loader.timeTaken > 5000 )
				animation_delay = Loader.timeTaken * 5;
			
		  Loader.loopingLoaderArrow(animation_delay);
    
    
    if(flashSound) flashSound.play('buttonClick1');
    this.updateNavigation(url);
    // Build the new URL in HTMLF format, checking for query strings
    if (url.indexOf("?") > -1) {
      url = url.replace("?", ".htmlf?");
    }
    else {
      url = url + ".htmlf";
    }
    if(this.shortened) url += '?shortened=true';
		// Ajax request to bring data for requested page. it also calculates time taken by this request.
    this.pendingRequest = $.ajax( { 
			url: url,
			success: Loader.initPage,
			beforeSend: function(request){
				Loader.timeBefore = (new Date().getTime()); // current time stamp for calculating time takens
				}
		 }	
		);		
	},
  click: function(e) {
    var url = $(this).attr("href");
    Loader.get(url);
    e.preventDefault();
  },
  fadeOutComplete: function() {
    Loader.fadeCompleted = true;
    if(Loader.shortened){
      $("#content").remove();
    } else {
      Loader.container.empty();
      $("body").attr("id", null);
    }
    Loader.checkRequestAndFade();
  },
  initPage: function(content) {
		var timeAfter = (new Date().getTime());
		var currentReqTimeTaken = (timeAfter - Loader.timeBefore ) ;
		//update timetaken only if current request took more time than previous longest request or if timetake == 6000. this is initial value
		if(Loader.timeTaken < currentReqTimeTaken || Loader.timeTaken == 6000){ 
			Loader.timeTaken = currentReqTimeTaken ; // time difference in milisecs
		}		
    Loader.contentCache = content;
    Loader.requestCompleted = true;
    delete Loader.pendingRequest;
    Loader.checkRequestAndFade();
  },
  checkRequestAndFade:function(){
    if(Loader.requestCompleted && Loader.fadeCompleted){
      Loader.setupHTML();
    }
  },
  setupHTML:function(){
    if(Loader.shortened){
      var content = $(Loader.contentCache).css({opacity:"0"});
      Loader.container.find("#sub-sub-nav").after(content);
      $("#content").paginate();
      Loader.loaderDialArrow.stop().animate({left:Loader.loaderDialArrowEnd}, 500, function(){
        content.animate({opacity:"1"}, 500, "linear");
      });
      
    } else {
      Loader.container.html(Loader.contentCache);
      var title = $("h1:first").text();
      Sections.discover();
      Loader.preloadBackground();
    }
    
    if(!Loader.isBase) $.ajaxHistory.addHistory(Loader.currentURL, title); //only add this url to history if we havent backed to the start page - eg hash of ''
    Loader.isBase = false; //set isBase to false for next time
    //Google Tracking 
    //pageTracker._trackPageview($.ajaxHistory.makeSlug(document.title));
  },
  preloadBackground:function(){
    this.imagePreloader.empty();
    if($("#container").css('backgroundImage').length > 4){//it needs to be at least '1.jpg' or something longer
      url = $("#container").css('backgroundImage').replace(/"|'|url|\(|\)/g, '');
      var img = $('<img />');
      img.load(function(){
        Loader.fadeIn();
      });
      img.attr('src', url);
      this.imagePreloader.append(img);
    } else {
      Loader.fadeIn();
    }
  },
  fadeIn:function(){
    Loader.loaderDialArrow.stop().animate({left:Loader.loaderDialArrowEnd}, 500, function(){
      Loader.containerOverlay.animate({opacity: 0}, 1000, "linear", function(){
        $(this).css({display:"none"});
      });
    });
  },
  flashMenuReady:function(){
    Loader.flashMenu = $("#flashMenuReplace").get(0);
    Loader.updateNavigation();
  },
  updateNavigation: function(url) {
    if (Loader.flashMenu && Loader.flashMenu.setURL){
      if(!url) url = Loader.currentURL;
      if(url){
        url = url.replace(Loader.hostAndProtocol);
        Loader.flashMenu.setURL(url);
      }
    }
  }
};

// Handles the initialisation of each section. Sets body ID or calls any
// custom initalisation.
var Sections = {
  discover: function() {
    for (var i=0; i < Sections.entries.length; i++) {
      var current = Sections.entries[i];
      var match = $(current.matcher);
      if (match.length > 0) {
        this.currentSection = current;
        if (current.sectionID) $("body").attr("id", current.sectionID);
        Sections.initCommon();
        if (current.init) current.init(match);
        return;
      }
    }
  },
  initCommon: function() {
    
    $("#content").paginate();
    
    $("#hand-navigation a").click(function(){
      flashSound.play('buttonClick1');
    });
    
    //flash heading replacement
    var textProps = {color: "0x64190F", size: "30", yOffset: "-2", xOffset: "-4", textTransform: "uppercase", letterSpacing:2};
    if(Sections.currentSection.sectionID == "beer-n-grub-three-c") textProps.color = '0xFFFFFF';
    $("#container h1").flashComplexImageReplacement(
      "/flash/text-replace.swf",
      {base: textProps}
    );
    
    // Attach the click event to any anchor that is:
    // - in the container
    // - has a href with a URL in it i.e. won’t bind on controls inserted by JS.
    $("a[href]:not([rel*=lightbox],[class*=popup])").unbind('click').click(Loader.click);
    
    $("a.popup").unbind('click').click(function(){
      GB_showCenter(false, $(this).attr('href'), 600, 600);
      return false;
    });
    
  },
  register: function() {
    for (var i=0; i < arguments.length; i++) {
      this.entries.push(arguments[i]);
    };
  },
  entries: []
};

// Register the sections that need to be initialised on load
// Splash page
Sections.register({
  matcher:"#splash-image",
  sectionID:"splash",
  init: function(){
    var textProps = {font:"Arial", bold:"false", color: "0x64190F", size: "15.75", xOffset: "-4", letterSpacing:"0.6", lineHeight:"3"};
    $("#splash-paragraph").flashComplexImageReplacement(
      "/flash/text-replace.swf",
      {base: textProps}
    );
  }
})  
// The Wall
Sections.register(
  {
    matcher: "#the-wall-title", 
    sectionID: "the-wall",
    init: function() {
      $("#radioRollover").mouseover(function(){ flashSound.play('theWallRadio') });
    }
  },
  {
    matcher: "#the-wall-awards-title", 
    sectionID: "the-wall-awards",
    init: function() {
      $("#awardsRollover1, #awardsRollover2, #awardsRollover3, #awardsRollover4").mouseover(function(){ flashSound.play('theWallAwards') });
    }
  },
  {
    matcher: "#the-wall-news-title", 
    sectionID: "the-wall-news",
    init: function() {
      $("#coffeeRollover").mouseover(function(){ flashSound.play('coffeeMachine') });
    }
  }
);

function initBeerSection() {
  $("#sub-sub-nav a").each(function(i, a) {
    a = $(a);
    if(a.attr('id') != "getsome"){
      var newLink = a.attr("href") + "?shortened=true"
      a.attr("href", newLink);
      a.click(function(){
        $(this).parent().attr('class', 'current');
        $(this).parent().siblings().attr('class', 'default');
      });
    }
  });
}

// Our Beer
Sections.register(
  {matcher: "#our-beer-alpha-title", sectionID: "our-beer-alpha", init: initBeerSection},
  {matcher: "#our-beer-dogbolter-title", sectionID: "our-beer-dogbolter", init: initBeerSection},
  {matcher: "#our-beer-bohemian-title", sectionID: "our-beer-bohemian", init: initBeerSection},
  {matcher: "#our-beer-beez-neez-title", sectionID: "our-beer-beez-neez", init: initBeerSection},
  {matcher: "#our-beer-fat-yak-title", sectionID: "our-beer-fat-yak", init: initBeerSection},
  {matcher: "#our-beer-redback-title", sectionID: "our-beer-redback", init: initBeerSection},
  {matcher: "#our-beer-big-helga-title", sectionID: "our-beer-big-helga", init: initBeerSection},
  {matcher: "#map_menu", sectionID: "beer-map"},
  {matcher: "#our-beer-seasonal-title", sectionID: "our-beer-seasonal", init: initBeerSection},
  {
    matcher: "#beer_menu",
    sectionID: "beer-range",
    init: function() {
      flashXMLfromHTML({swf: "/flash/beer_menu.swf", targetElements: $("#beer_menu"), id: "flashBeerMenu"});
    }
  }
);
// Brewer’s Bit
Sections.register(
  {matcher: "#blog-title", sectionID: "blog"},
  {matcher: "#forum-title", sectionID: "forum"},
  {matcher: "#links-title", sectionID: "links"},
  {
    matcher: "#gallery-overlay", 
    sectionID: "gallery",
    init: function(match) {
      setupLightbox();
    }
  }
);
// Beer ‘n’ grub
Sections.register(
  {
    matcher: "#beer-n-grub-three-c-title", 
    sectionID: "beer-n-grub-three-c",
    init: function() {
      $("#cutoutRollover").mouseover(function(){ flashSound.play('beerGrubKitchen') });
    }
  },
  {matcher: "#beer-n-grub-title", sectionID: "beer-n-grub"}
);
// Misc
Sections.register(
  {
    matcher: "#garage-wear-title", 
    sectionID: "garage-wear",
    init: function(match) {
      
      $("#lockerDoor").mouseover(function(){
        flashSound.play('garageWearLockerDoor') 
        $(this).addClass("hover");
      }).mouseout(function(){
        $(this).removeClass("hover");
      });
      
    }
  },
  {matcher: "#beer-stations-title", sectionID: "beer-stations"},
  {
    matcher: "#stockist-search-title", 
    sectionID: "stockist-search",
    init: function(){
      if($.browser.msie && parseInt($.browser.version.split(".")[0]) < 7) DD_belatedPNG.fix('#container');
      $("#content form").submit(function(e) {
        var form = $(this);
        // Build query string
        var query = []
        form.find(":input:not(button)").each(function(i, input) {
          query.push($(input).attr("name") + "=" + $(input).val());
        });
        var url = form.attr("action") + "?" + query.join("&");
        Loader.get(url)
        return false;
      })
    }
  },
  {
    matcher: "#contact-title", 
    sectionID: "contact",
    init: function() {
      $("#phoneRollover").mouseover(function(){ flashSound.play('phoneRing') });
      Contact.init();
      Enquiry.init();
    }
  }
);

//Contact Form
//No validation is done.
var Enquiry = {
  
  init: function(){
    $("#contact-form .submit").unbind().click(Enquiry.submit);
  },
    
  submit: function(vars){
    
    Valid = ($("#contact-form").valid());
    
    if (Valid == false){
      return false;
    } else {
      
    };
    
    var elements = $("#contact-form").find("input, select, textarea");
    var vars = {};
    elements.attr("style", " ");
    elements.each(function(){
      if(this.type == "radio"){
        if(this.checked) vars[this.name] = this.value;
      } else if(this.type == "checkbox"){
        if(this.checked) vars[this.name] = this.value;
      } else {
        vars[this.name] = this.value;
      }
    });
    
    vars.ajax = true;
    
    if (Enquiry.pendingRequest) Enquiry.pendingRequest.abort();
    
    Enquiry.pendingRequest = $.post( "/email_enquiry", vars, Enquiry.requestComplete);
    
    //prevent default action
    return false;
    
  },
  
  requestComplete: function(result){
    
    Enquiry.pendingRequest = null;
    
    var resultJSON = eval('('+result+')');
    
    Enquiry.success();
  },
  
  success: function(){
    Enquiry.createFeedbackElement();
    Enquiry.feedbackElement.append($("<p>Thank you for your comments.</p>"));
    Enquiry.feedbackElement.hide();
    Enquiry.feedbackElement.slideDown(Enquiry.animationDuration);
  },
  
  createFeedbackElement: function(){
    //remove any previous feedback elements
    if(Enquiry.feedbackElement) Enquiry.feedbackElement.stop().slideUp(Enquiry.animationDuration, function(){
      $(this).remove();
    });
    
    Enquiry.feedbackElement = $("<div class='form-feedback'></div>");
    $("#contact-form").prepend(Enquiry.feedbackElement);
  }
  
};

//Join the club Form
//No validation is done.
var Contact = {
      
  init: function(){
    $("#club-form .submit").unbind().click(Contact.submit);
  },
    
  submit: function(vars){
    
    Valid = ($("#club-form").valid());
    
    if (Valid == false){
      return false;
    } else {
      
    };
    
    var elements = $("#club-form").find("input, select, textarea");
    var vars = {};
    elements.attr("style", " ");
    elements.each(function(){
      if(this.type == "radio"){
        if(this.checked) vars[this.name] = this.value;
      } else if(this.type == "checkbox"){
        if(this.checked) vars[this.name] = this.value;
      } else {
        vars[this.name] = this.value;
      }
    });
    
    vars.ajax = true;
    
    if (Contact.pendingRequest) Contact.pendingRequest.abort();
    
    Contact.pendingRequest = $.post( "/join_the_club", vars, Contact.requestComplete);
    
    //prevent default action
    return false;
    
  },
  
  requestComplete: function(result){
    
    Contact.pendingRequest = null;
    
    var resultJSON = eval('('+result+')');
    
    Contact.success();
  },
  
  success: function(){
    Contact.createFeedbackElement();
    Contact.feedbackElement.append($("<p>Thankyou for joining the club</p>"));
    Contact.feedbackElement.hide();
    Contact.feedbackElement.slideDown(Contact.animationDuration);
  },
    
  createFeedbackElement: function(){
    //remove any previous feedback elements
    if(Contact.feedbackElement) Contact.feedbackElement.stop().slideUp(Contact.animationDuration, function(){
      $(this).remove();
    });
    
    Contact.feedbackElement = $("<div class='form-feedback'></div>");
    $("#club-form").prepend(Contact.feedbackElement);
  }
  
};

//Do Lightbox Stuff
function setupLightbox(){
  
  var galleryImages = $('#gallery-images');
  var galleryOverlay = $('#gallery-overlay');
  
  var imagesOverlay = $('<div id="gallery-images-overlay"></div>');
  
  $("#container").prepend(imagesOverlay);
  
  imagesOverlay.append(galleryImages.find("li").clone());
  imagesOverlay.find("a").empty();
  
  imagesOverlay.find("a[rel*=lightbox]").lightBox({
    showImageData:  false,
    containerBorderSize: 20,
    containerBorderBottomExtra: 40,
    fixedNavigation:true,
    imageLoading:		'/javascripts/lightbox/images/lightbox-ico-loading_2.gif',		// (string) Path and the name of the loading icon
		imageBtnPrev:		'/javascripts/lightbox/images/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
		imageBtnNext:		'/javascripts/lightbox/images/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
		imageBtnClose:	'/javascripts/lightbox/images/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
		imageBlank:			'/javascripts/lightbox/images/lightbox-blank.gif'
  });
}
//setup greybox for ajax popups
var GB_ROOT_DIR = "/javascripts/greybox/";
// Fire away! Heave-to, load those harpoons! At him boys,
// lest the monstrous beast dip below and get away.
$(document).ready(function() {
  Loader.init();
});