// analytics
var google_analytics = $('meta[name=google-analytics]').attr('content');
var hostname         = document.domain.replace("www.","").toLowerCase();
var trackable        = true;
if (trackable) {
  $.trackPage(google_analytics);
}

var graceful = ($.system.os.iphone || $.system.os.ipod || $.system.os.blackberry);

// function unloadact() {  }, prevent user back button cache
history.navigationMode = 'compatible';
$(document).ready(function() {
  function checkMe() {
    var check = {
      window_width: $(window).width(),
      window_height: $(window).height(),
      body_bottom: $(".body").offset().top,
      body_bottom_with_direct_selector: $(".document > .body").offset().top
    }
    
    for (var checker in check) {
      alert(checker + ": " + check[checker]);
    }
  }
  
  $("body").unload(function() {
    
  })
  var postOpacity = $(".post").css("opacity");
  $(".background").css("opacity", 0).animate({opacity:1}, 300);
  $(".post").css("opacity", 0).delay(100).animate({opacity:postOpacity}, 400, function() {
  });
  // don't want to be able to select the background images
	$(".background").live("dragstart", function() {
		return false;
	});
	
	// main menu animations
	
	var mainSelected = null;
	function mainMenuSelector(link) {
    var name = link.text().replace(/^\s+|\s+$/, "");
    link.addClass("selected");
    link = link.parent("li");
    link.addClass("selected");
    mainSelected = link;
    $("#selector").append("<span>" + name.toUpperCase() + "</span>");
    $("#selector").css("left", link.offset().left - 10).css("display", "block")
      .css("top", -100)
        .delay(200)
        .animate({top:link.offset().top - 40}, 300);
	}
	
	var currentUrl = window.location.href;//"http://press.josephjewell.com";//window.location.href;
	var currentHost = window.location.host;//"press.josephjewell.com";//window.location.host;
  var links = [];
	$(".header .menu a").each(function() {
	  links.push({menu: this.href.replace(/\/$/, ""), element:$(this)});
	});
	
	
	var linkMatches = [];
	for (var i = 0; i < links.length; i++) {
	  var menu = links[i].menu;
	  var a = menu == currentUrl.replace(/(\/)?$/, "")
	  var b = menu == currentUrl.replace(/\/[^\/]+(\/)?$/, "")
	  var c = menu == currentUrl.replace(/(\/)?$/, "").replace("http://" + currentHost, "")
	  var d = menu == currentUrl.replace(/\/[^\/]+(\/)?$/, "").replace("http://" + currentHost, "")
	  if (a || b || c || d) {
	    if (linkMatches.length > 0 && linkMatches[0].menu.length < menu.length) {
	      linkMatches.pop();
	      linkMatches.push(links[i])
	    } else {
	      linkMatches.push(links[i])
	    }
	  }
	}

  mainMenuSelector(linkMatches.pop().element);
    
	links = [];
	var found = false;
	$(".body .subpages a").each(function() {
	  links.push({menu:this.href.replace(/\/$/, ""), element:$(this)});
  });
  
	links = links.sort(function(a, b) {
	  a.menu.length > b.menu.length
	})
	
	var subSelected = null;
  for (var i = 0; i < links.length; i++) {
    var menu = links[i].menu
	  var a = menu == currentUrl.replace(/(\/)?$/, "")
	  var b = menu == currentUrl.replace(/\/[^\/]+(\/)?$/, "")
	  var c = menu == currentUrl.replace(/(\/)?$/, "").replace("http://" + currentHost, "")
	  var d = menu == currentUrl.replace(/\/[^\/]+(\/)?$/, "").replace("http://" + currentHost, "")
	  if (a || b || c || d) {
      var link = links[i].element;
      var name = link.text();
      link.addClass("selected");
      link = link.parent("li");
      link.addClass("selected");
      subSelected = link;
      $("#subpages-selector").css("display", "block").append("<span>" + name.toUpperCase() + "</span>");
      $("#subpages-selector").css("left", link.offset().left - 200)
        .css("opacity", 0)
        .css("top", link.offset().top)
          .delay(300)
          .animate({
            left:link.offset().left - 50,
            opacity: 1
          }, 500);
	    break;
	  }
	}
	
	links = null;
  $(".document > .body a").each(function(index, element) {
    var item    = $(element);
    var href    = item.attr("href").toLowerCase();
    var remote  = (href.indexOf("http://") !=- 1 && (href.indexOf(hostname) == -1));

    if (remote) {
      item.addClass("external");
      //item.attr("target", "_blank");
    } else {
      item.addClass("internal");
    }
  });
  
  $(".document > .header .menu a").addClass("transition");
  $(".document > .body .subpages a").addClass("transition");
  
  var linkLocation = null;
  function redirectPage() {
    window.location = linkLocation;
  }
	
  $("a.transition").click(function() {
    var link = $(this);
  	if (link.hasClass("external") || $.system.browser.firefox)
  		return true;
    linkLocation = this.href;
    setTimeout(changePage, 20);
    return false;
  });
  $.cookie("previousUrl", window.location.href, {path:"/"});
  
  function changePage() {
    // can't handle it!
    // $("#subpages-selector").animate({left:-100, opacity: 0}, 300);
    $("#selector").delay(40).animate({top:-100}, 300);
    $(".background").animate({opacity:0}, 300);
    $(".post").delay(100).animate({opacity:0}, 400);
    $("body").delay(200).animate({opacity:0}, 400, function() {
      window.location = linkLocation;
    })
  	return false;
  }
	
  $.fn.stickyFooter = function(options) {
    var $window   = $(window);
  	var $above     = $(options.above);
  	var $footer   = $(this);
    
  	var initialPosition = $footer.offset().top;
  	var initialHeight   = $footer.height();
  	
  	$footer.css("visibility", "hidden");
  	$footer.width("100%");
    $footer.css({position: "absolute", top:initialPosition});
    // lowest top
		
  	setTimeout(function() {
  	  var maxHeight = $(document).height();
      var positionFooter = function() {
    		var boundary = $above.offset().top + $above.height();
    		var footerBottom = $footer.offset().top + $footer.height();
    		var windowBottom = $window.height() + $window.scrollTop();
    		if (footerBottom <= windowBottom && $footer.offset().top >= initialPosition) {
    		  $footer.css("top", windowBottom - $footer.height() - 1); // border == 1
    		} else {
    			$footer.css("top", initialPosition);
    		}
      }
      
    	$footer.css("visibility", "visible");
      positionFooter();
      
    	$window.resize(positionFooter);
    	$window.scroll(positionFooter);
    	
  	}, 500)
  }
	
	$(".document > .footer").stickyFooter({
	  above: ".document > .body"
	});
  // slideshow
  if ($('#large-slide').get(0)) {
    $('#large-slide').after("<div id='nav'>").cycle({
      fx: 'fade',
      timeout: 3000,
      pager: '#nav',
      speed: 1000,
      pagerEvent: 'click',
      pauseOnPagerHover: true,
      cleartypeNoBg: true
    });
  } else {
  }
  
  $(".main a").hover(function() {
    $(this).stop().animate({opacity:.7}, 100);
  }, function() {
    $(this).stop().animate({opacity:1}, 100);
  });
  
  var $selector = $("#selector");
  var $subselector = $("#subpages-selector");
  $(window).resize(function() {
    $selector.css("left", mainSelected.offset().left - 10);
    $subselector.css("left", subSelected.offset().left - 50);
  });
  
  var picasaUserId = "114736267714313794052";
  var picasaGalleryId;
  try {
    picasaGalleryId = $('.post').attr('class').match(/gallery-(\d+)/)[1];
  } catch (error) {}
  
  if (picasaGalleryId) {
   
    $.picasa.images(picasaUserId, picasaGalleryId, function(images) {
      var picasaAlbum = "<div class='slideshow' id='small-slideshow'>\n"
      var first = false;
      var last = false;
      $.each(images, function(i, element) {
        first = (i == 0 || i % 3 == 0)
        last = ((i + 1) % 3 == 0)
        if (first)
          picasaAlbum += "<ul class='slide'>\n";
        var classes = 'figure'
        if (last)
          classes += " last";
        picasaAlbum += "  <li class='" + classes + "'>\n";
        picasaAlbum += "    <a class='pretty-photo' rel='prettyPhoto[gallery]' href='" + element.url + "'>\n";
        picasaAlbum += "      <img class='picasa-image-thumb' height='147' src='" + element.thumbs[2].url + "'/>\n";
        picasaAlbum += "    </a>\n";
        picasaAlbum += "  </li>\n";
        var after_last = (i == images.length - 1 || (i + 2) % 4 == 0)
        if (last)
          picasaAlbum += "</ul>";
      });
      picasaAlbum += "</div>";
      $("#small-slideshow").replaceWith(picasaAlbum);

    	$("a.pretty-photo").prettyPhoto({
    		theme:'dark_rounded',
    		autoplay: true // autoplay videos
    	});

    	$('#small-slideshow').cycle({
    		timeout:		 4000,	// milliseconds between slide transitions (0 to disable auto advance)
    		fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
    		next: '#next',	// selector for element to use as click trigger for next slide
    		prev: '#prev',	// selector for element to use as click trigger for previous slide
    		pause:			 1,		// true to enable "pause on hover"
    		pauseOnPagerHover: 1 // true to pause when hovering over pager link
    	});
    }); 
  }
  var authorized = false;
  
  RegExp.escape = function(str)
  {
    var specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
    return str.replace(specials, "\\$&");
  }
  
  $.secretPhrase = function(phrase, callback) {
    var current = "";
    var typing = false;
    var interval = null;
    
    var reset = function() {
      current = "";
    }
    var clear = function() {
      typing = false;
      if (interval) {
        clearTimeout(interval);
        interval = null;
      }
      reset();
    }
    var attempt = function() {
      if (interval) {
        clearTimeout(interval);
        interval = null;
      }
      interval = setTimeout(clear, 750);
      typing = true;
    }
    var success = function() {
      callback();
      clear();
    }
    var update = function(character) {
      current += character;
      if (phrase.match(new RegExp(RegExp.escape(current), "i"))) {
        if (current == phrase) {
          success();
        } else {
          attempt();
        }
      } else {
        clear();
      }
    }
    
    $(window).keydown(function(event) {
      var character = String.fromCharCode(event.charCode || event.keyCode);
      if (character && !$(event.target).is("textarea"))
        update(character.toLowerCase());
    });
  }
  
  // admin
  var postArea = [$(".post")];
  
  var authorized = $.cookie("authorized");
  var textChanged = false;
  
  $.secretPhrase("login", function() {
    $.ajax({
      url: "/login",
      success: function(data) {
        authorized = true;
        $.cookie("authorized", true, {path:"/"});
        var thumbsUp = $("<img id='thumbs-up' src='/images/thumbs-up-icon.png'/>");
        thumbsUp.css("position", "fixed");
        thumbsUp.css("opacity", "0");
        $("body").append(thumbsUp);
        thumbsUp.css("bottom", 10);
        thumbsUp.css("left", 10);
        thumbsUp.animate({opacity:1}, 300).delay(1200).animate({opacity:0}, 300, function() {
          thumbsUp.remove();
        });
      }
    })
  });
  
  $.secretPhrase("logout", function() {
    $.cookie("authorized", null);
    authorized = false;
  });
  
  function postClickHandler() {
    if (!authorized) {
      return;
    }
    var post = $(this);
    var classes = post.attr("class");
    if (post.is("textarea")) {
      if (textChanged) {
        postArea[0].attr("data-raw", post.val());
        $.ajax({
          type: "POST",
          url: "/posts/" + postArea[0].attr("id"),
          dataType: "json",
          data: {post:post.val()},
          success: function(data) {
            //var old = postArea[0];
            //postArea[0] = $(data);
            //old.replaceWith(postArea[0]);
            var post = data.post;
            $("h1", postArea[0]).text(post.title);
            $("h2", postArea[0]).text(post.subtitle);
            $("#subpages-selector span").text(post.menu_title.toUpperCase());
            $(".entry-content", postArea[0]).html(post.body);
          }
        });
        textChanged = false;
      }
      post.replaceWith(postArea[0]);
    } else {
      var raw = post.attr("data-raw");
      if (raw) {
        var textarea = postArea[1];
        textarea.val(raw);
        textarea.height(post.height());
        post.replaceWith(textarea);
        textarea.focus();
      } else {
        $.ajax({
          url: window.location.href.replace(/\/$/, "") + "/raw",
          success: function(yaml) {
            var textarea = $("<textarea class='" + classes + "'>" + yaml + "</textarea>");
            textarea.height(post.height());
            postArea.push(textarea);
            post.replaceWith(textarea);
            post.attr("data-raw", yaml);
            textarea.focus();
          }
        });
      }
    }
  }
  $("article.post").live("click", postClickHandler);
  $("textarea.post").live("blur", postClickHandler).live("change", function() {
    textChanged = true;
    postClickHandler();
  });
  
});

var WRInitTime=(new Date()).getTime();
