var didResize = false,
  $imageWrapper = false;
$browserWindow = false,
  $dropdown = false,
  $content = false,
  $footer = false,
  $loader = false,
  loaderTO = false,
  $pageLoader = false,
  $bar = false,
  $next = false,
  $prev = false,
  $navArrow = false,
  $spinner = false,
  $quotes = false,
  $individualQuotes = false,
  cursorPositionX = 0,
  cursorPositionY = 0,
  browserWidth = 0,
  browserHeight = 0,
  headerHeight = 44,
  footerHeight = 30,
  contentHeight = 700,
  loaderTimeout = false,
  slideTimeout = false,
  pageLoaderTimout = false,
  quotesTimeout = false,
  slideInterval = 7000,
  dropdownState = false,
  assetsLoaded = 0,
  assetsToLoad = [],
  slideShowLength = 0,
  slideShowPosition = 0,
  oldSlideShowPosition = 0,
  inIFrame = false,
  previousSelected = false;

/**
* DOM Load
*/
setInterval(function () {
  if (didResize) {
    didResize = false;
    layout();
  }
}, 15);
$(document).ready(function () {
  pageEnhance();
  setupHistory();
  previousSelected = $("nav a.selected");
});

function setupHistory() {
  var History = window.History;
  // Prepare
  if (!History.enabled) {
    // History.js is disabled for this browser.
    // This is because we can optionally choose to support HTML4 browsers or not.
    return false;
  }

  var State = History.getState();
  if (State.cleanUrl != document.URL) {
    loadPage(State.cleanUrl);
  }

  // Bind to StateChange Event
  History.Adapter.bind(window, 'statechange', function () { // Note: We are using statechange instead of popstate
    var State = History.getState(); // Note: We are using History.getState() instead of event.state
    loadPage(State.cleanUrl);
  });
}



/**
* General "init" function
*/
function pageEnhance() {

  if ($("body").hasClass("iframe")) {
    inIFrame = true;
  }

  if (!inIFrame) {
    // Create loader
    $loader = $('<div id="loader"><div id="lTop"><div id="loaderLogo"></div></div><div id="lBtm"></div><div id="progress"><div id="bar"></div></div></div>');
    $("body").append($loader);
    $bar = $("#bar");
    // Array of images we need to load
    assetsToLoad.push('/images/loadingLogo.gif');
    assetsToLoad.push('/images/logo.png');
    assetsToLoad.push('/images/loader.png');
    assetsToLoad.push('/images/prevnext.png');
    assetsToLoad.push('/images/navArrow.png');
    assetsToLoad.push('/images/bullet.png');
    $("#imageWrapper img").each(function () {
      assetsToLoad.push($(this).attr("src"))
    })

    // Run initital loader
    loaderTO = setTimeout(function () { assetsLoaded = 100; }, 10000);
    $.imgpreload(assetsToLoad, {
      each: function () {
        assetsLoaded++;
        initLoader();
      }
    });

    // Grab some elements for common reuse
    $imageWrapper = $("#imageWrapper");
    $browserWindow = $(window);
    $content = $("#content");
    $dropdown = $("#dropdown");
    $footer = $("footer");

    // Resize event
    $browserWindow.resize(function () {
      didResize = true;
    })

    // Main layout function
    $navArrow = $('<div id="navArrow" />');
    $("nav").append($navArrow);
    layout();

    // Quotes
    initQuotes();


    // Ajaxify
    $("a.page").live("click", function () {
      href = $(this).attr("href");
      History.pushState(null, $(this).text(), href);
      //loadPage(href);
      clearSelectedNav();
      $(this).addClass("selected");
      $('a[href*="/contact-us/"]').attr("href", "/contact-us/?iframe=true&src=http://www.luxurychaletcollection.com" + href);
      return false;
    });

    $("a.dropdown").click(function () {
      href = $(this).attr("href");
      if (dropdownState == href) {
        dropdown(href, "toggle");
        clearSelectedNav();
        previousSelected.addClass("selected");
      } else {
        dropdown(href, "show");
        
        previousSelected = $("nav a.selected");
        if (previousSelected.length == 0) {
          previousSelected = $("footer a.selected");
        }

        clearSelectedNav();
        $(this).addClass("selected");
      }
      dropdownState = href;
      return false;
    });

    $("a.modal").click(function () {
      if ($dropdown.hasClass("active")) {
        dropdownHide();
      }
    });

    $("nav a").hover(function () {
      navArrowPosition($(this))
    },
			function () {
			  navArrowPosition($("nav a.selected"))
		});
			

    $(".gridNav li a").live("hover", function (event) {
      if (event.type == "mouseenter") {
        $(this).find("p").stop(true,true).show()
      } else {
        $(this).find("p").stop(true, true).fadeOut()
      }
    });

    $("#imageNav").live("hover", function (event) {
      if (event.type == "mouseenter") {
        $(this).find("ul").stop().animate({ top: "0" }, 300)
      } else {
        $(this).find("ul").stop().animate({ top: "67px" }, 1000)
      }
    });

    $("#imageNav ul li a:not(.selected)").live("hover click", function (event) {
      if (event.type == "mouseenter") {
        $(this).stop().animate({ "background-color": "#273347" })
      } else if (event.type == "click") {
        i = parseInt($(this).attr("href").split("bg")[1]) - 1;
        clearTimeout(slideTimeout);
        slideShowPosition = i - 1;
        $next.click();
        return false;
      } else {
        $(this).stop().animate({ "background-color": "#fff" });
      }
    });

    $("#showInfo").live("click", function () {
      if ($(this).hasClass("open")) {
        $(this).removeClass("open").html("Show Info");
        $("#slideDown").stop(true, true).slideUp(500, "easeOutCirc");
      } else {
        $(this).addClass("open").html("Hide Info");
        $("#slideDown").stop(true, true).slideDown(1000, "easeOutCirc");
      }
      return false;
    });
    $("#hideInfo").live("click", function () {
      $("#showInfo").click();
      return false;
    });
    $("#showPanel").live("click", function () {
      $("#showInfo").click();
      return false;
    });
    $("#showPanel").live("mouseenter", function () {
      $("#showInfo").addClass("hover");
    });
    $("#showPanel").live("mouseleave", function () {
      $("#showInfo").removeClass("hover");
    });
    

    addFancyBox();
  }
  newWindowLinks();
}

function addFancyBox() {
  $("a.modal").each(function () {
    h = $(this).attr("href");
    if (h.indexOf("?") != -1) {
      h = /(iframe=true)/g.test(h) ? h : h + "&iframe=true";
    } else {
      h = /(iframe=true)/g.test(h) ? h : h + "?iframe=true";
    }
    $(this).attr("href", h);
  }).unbind("click.fb").fancybox({
    'type': "iframe",
    'hideOnContentClick': true,
    'width': 582,
    'height': 582,
    'scrolling': 'no',
    'overlayColor': '#000000',
    'transitionIn': 'elastic',
    'transitionOut': 'elastic',
    'speedIn': 600,
    'speedOut': 200,
    'modal': false
  });
}

function dropdown(href, state) {

  state = state || "toggle";

  if ((state == "toggle" && $dropdown.hasClass("active")) || state == "hide") {
    dropdownHide();
    $navArrow.show();
  } else {
    $dropdown.stop();
    $navArrow.hide();
    $.ajax({
      type: "GET",
      url: href,
      data: "ajax=true",
      success: function (msg) {
        $navHTML = $(msg).find(".gridNav").addClass("content");
        $dropdown.html($navHTML);
        $dropdown.addClass("active")
        layout();
        $dropdown.animate({ top: "0" }, {
          "easing": "easeOutCirc",
          "duration": 900,
          "complete": function () {
            loadAndFadeIn($navHTML.find("img"))
          }
        })
      }
    });
  }

}
function clearSelectedNav() {
  $("nav a").removeClass("selected");
  $("footer a").removeClass("selected");
}

function dropdownHide(speed) {
  speed = speed || 1500
  $dropdown.removeClass("active").stop().animate({ top: "-" + $dropdown.css("height") }, {
    "easing": "easeOutCirc",
    "duration": speed
  })
}
function loadPage(href) {
  $("#loaderBG").show();
  clearTimeout(slideTimeout);
  dropdownHide(500);
  setTimeout(function () {
    showLoader()
    $content.fadeOut();
    $("header").fadeOut();
    if ($next) {
      $next.hide();
      $prev.hide();
    }
    $imageWrapper.fadeOut(function () {
      $.ajax({
        type: "GET",
        url: href,
        data: "ajax=true",
        success: function (msg) {
          clearTimeout(quotesTimeout);
          var html = $(msg);

          newContent = html.find("#content").html();
          newImagesHTML = html.find("#slideWrapper").html();

          // Load the first 2 images
          $newImages = html.find("#slideWrapper img:lt(2)");
          assetsLoaded = 1;
          advancePageLoaderBar(assetsLoaded, $newImages.size());
          $newImages.imgpreload({
            each: function () {
              assetsLoaded++;
              advancePageLoaderBar(assetsLoaded, $newImages.size());
            },
            all: function () {
              // Preload the next images
              $nextImages = html.find("#slideWrapper img:gt(1)");
              $nextImages.imgpreload();

              _gaq.push(['_trackPageview', href]);

              clearTimeout(pageLoaderTimout);
              $pageLoader.fadeOut(100);
              $content.stop(true, true).html(newContent).fadeIn(300, function () {
                addFancyBox();
                initQuotes();
              });
              $imageWrapper.html(newImagesHTML).fadeIn();
              layout();
              slideShowPosition = 0;
              slideshowInit();
              $("header").fadeIn();
              $("#navArrow").fadeIn();
              $("#loaderBG").hide();
            }
          });
        }
      });
    })
  }, 500)
}

function initQuotes() {

  $quotes = $("#quotes");
  $individualQuotes = $quotes.find("li");

  if ($individualQuotes.size() > 1) {
    quotesTimeout = setInterval(function () {
      var currentQuoteIndex = $individualQuotes.index($("li:visible"));
      currentQuoteIndex = currentQuoteIndex < 0 ? 0 : currentQuoteIndex;
      showIndex = currentQuoteIndex + 1;
      if (showIndex > $individualQuotes.size() - 1) {
        showIndex = 0;
      }
      $individualQuotes.eq(currentQuoteIndex).fadeOut(1000, function () {
        $individualQuotes.eq(showIndex).fadeIn(1000)
      })
    }, slideInterval)
  }
}



function loadAndFadeIn($jqObjects) {
  $jqObjects.imgpreload({
    each: function () {
      //$(this).hide().css({"visibility":"visible"}).fadeIn(1000)	
    },
    all: function (i) {
      $jqObjects.each(function (i) {
        $(this).hide().css({ "visibility": "visible" }).delay(i * 20).fadeIn(1000)
      })
    }
  });
}

function initLoader() {
  var percentageLoaded = (assetsLoaded / (assetsToLoad.length)) * 100;
  try {
    if (percentageLoaded >= 100) {
      clearTimeout(loaderTimeout);
      clearTimeout(loaderTO);
      $bar.stop().animate({ "width": "100%" }, 500, "linear", function () {
        slideshowInit();
        $("#loaderLogo").fadeOut(400, function () {
          $("#progress").hide();
          $("#lTop,#lBtm").animate({ height: 0 }, {
            "easing": "easeOutCirc",
            "duration": 1500
          })
          $loader.delay(1000).fadeOut(300, function () {
            $loader.remove();
            $bar, $loader = false;
          });
          loadAndFadeIn($content.find(".ldr img"));
        })
      });
    } else {
      $bar.stop().animate({ "width": percentageLoaded + "%" }, 300)
    }
  } catch (err) { }
}


// Main layout and resizing
function layout() {

  // Browser dimensions and Aspect ratio
  var minHeight = contentHeight + headerHeight + footerHeight;
  browserHeight = $browserWindow.height();
  browserHeight = browserHeight < minHeight ? minHeight : browserHeight;
  browserWidth = $browserWindow.width();
  var browserAspectW = browserWidth / browserHeight,
		browserAspectH = browserHeight / browserWidth;

  // Resize the images for "Fullscreen" effect	
  $imageWrapper.css({ height: browserHeight + "px" })
  $("#imageWrapper img,#loaderBG img").each(function () {
    // Calculate image aspect ratio & dimensions
    var iHeight = $(this).height(),
			iWidth = $(this).width(),
			iAspectW = iWidth / iHeight,
			iAspectH = iHeight / iWidth;

    if (browserAspectW > iAspectW) { // Size image based on based on screen width
      var newWidth = browserWidth,
					newHeight = iAspectH * newWidth,
					marginTop = -(newHeight - browserHeight) / 2,
					marginLeft = 0;
    } else { // Size image based on based on screen height
      var newHeight = browserHeight,
					newWidth = iAspectW * newHeight,
					marginTop = 0,
					marginLeft = -(newWidth - browserWidth) / 2;
    }
    $(this).css({ width: (newWidth) + "px", height: (newHeight) + "px", marginTop: marginTop + "px", marginLeft: marginLeft + "px" })
  });

  // Now center the content
  if (browserHeight > minHeight) { // we have enough room
    $(".content").css({ "top": headerHeight + ((browserHeight - minHeight) / 2) + "px" })
    $footer.css({ top: "auto", bottom: "0" })
  } else { // need page top scroll		
    $(".content").css({ "top": headerHeight + "px" })
    $footer.css({ bottom: "auto", top: (contentHeight + headerHeight) + "px" })
  }

  // Position nav arrow
  if ($("nav a.selected").length > 0) {
    navArrowPosition($("nav a.selected"));
  }

  // Grid nav
  if ($browserWindow.height() < (headerHeight + 700)) {
    $("body").addClass("smallGrid");
  } else {
    $("body").removeClass("smallGrid");
  }

  // Page scrolls?
  if ($dropdown.hasClass("active")) {
    if ($(document).height() > $browserWindow.height()) {
      $dropdown.css({ height: $(document).height() + "px" })
    } else {
      $dropdown.css({ height: "100%" });
    }
  } else {
    $dropdown.css({ height: "100%" });
  }
}

function setDropdownHeight() {
  
}

function navArrowPosition($target) {
  width = $target.width();
  offset = $target.offset().left;
  $navArrow.stop().animate({ left: (offset - (81 - width) / 2) + "px" })
}

/* *
* Construct the Homepage Hero area 
*/
function slideshowInit() {

  $(".slide:eq(0)").fadeIn(1000);
  $("#imageNav a:eq(0)").addClass("selected")
  slideShowLength = $(".slide").size();

  if (slideShowLength > 1 && !$next) {
    // Next button
    $next = $('<div id="next">Next</div>');
    $next.click(function () {
      clearTimeout(slideTimeout);
      nextIndex = slideShowPosition + 1;
      if (nextIndex > slideShowLength - 1) {
        nextIndex = 0;
      }
      slideshowSlide(nextIndex, "next")
    })
    $("body").append($next);

    // Previous button
    $prev = $('<div id="previous">Previous</div>');
    $prev.click(function () {
      clearTimeout(slideTimeout);
      prevIndex = slideShowPosition - 1;
      if (prevIndex < 0) {
        prevIndex = slideShowLength - 1;
      }
      slideshowSlide(prevIndex, "previous")
    })
    $("body").append($prev);
  }


  if (slideShowLength > 1 && $("#homeTitle").length == 0) {
    $next.show();
    $prev.show();
    
    if ($("#imageNav").size() > 0) {
      $("#imageNav").show();
    }
  } else {
    if ($next) {
      $next.hide();
      $prev.hide();
    }
    if ($("#imageNav").size() > 0) {
      $("#imageNav").hide();
    }
  }

  if (slideShowLength > 1) {
    // Set auto slideshow
    slideTimeout = setTimeout(function () {
      $next.click();
    }, slideInterval);
  }
}

function slideshowSlide(slideIndex, direction, mode) {

  var slideIndex = slideIndex || 0,
		direction = direction || "next",
		mode = mode || "crossfade",
		slide = $(".slide:eq(" + slideIndex + ")");

  var sliderPanelObj = $("#slideWrapper");

  // Nav
  $("#imageNav ul li a").stop().animate({ "background-color": "#fff" }).removeClass("selected");
  $("#imageNav ul li a:eq(" + slideIndex + ")").stop().animate({ "background-color": "#273347" }).addClass("selected");

  // Crossfade
  $(".slide").not(":eq(" + oldSlideShowPosition + ")").css({ zIndex: "1" });
  $(".slide:eq(" + oldSlideShowPosition + ")").stop(true, true).show().css({ zIndex: "9" });

  slide.hide().css({ zIndex: "10" }).fadeIn(1500, function () {
    $(".slide").not(":eq(" + slideShowPosition + ")").hide().css({ zIndex: "1" });
    slide.css({ zIndex: "1" })
  })

  // Update current slide position
  slideShowPosition = slideIndex;
  oldSlideShowPosition = slideShowPosition;

  slideTimeout = setTimeout(function () {
    $next.click();
  }, slideInterval);
}

/**
* animate page to a #elementid
*/
function inPageLinksScrollTo() {
  $(".scrollTo").click(function () {
    var href = $(this).attr("href");
    var target = $(href);
    if (target.size() > 0) {
      var offset = target.offset()
      $('html,body').animate({ scrollTop: offset.top }, 1000)
      return false;
    } else {
      return true;
    }
  })
}


/**	
* Target new windows
*/
function newWindowLinks() {
  $('a[rel=external]').live("click", function () {
    window.open($(this).attr('href'));
    return false;
  });
}

/**	
* Animate loaders
*/
function showLoader() {
  $loaderBG = $("#loaderBG");
  $loaderBG.html($imageWrapper.find("img:eq(" + slideShowPosition + ")"));
  if (!$pageLoader) {
    $bar = $('<div id="bar" />');
    $pageLoader = $('<div id="pageLoader"></div>');
    $pageLoader.append($spinner).append('<h2>Loading</h2>').append($bar)
    $bar.wrap('<div id="progress"></div>')
    $("body").append($pageLoader);
  } else {
    $bar.stop().css({ width: "0%" })
    $pageLoader.fadeIn()
  }

}

function advancePageLoaderBar(loaded, toLoad) {
  var percentageLoaded = (loaded / toLoad) * 100;
  $bar.stop().animate({ width: percentageLoaded + "%" }, 3000)
}
