jQuery.extend( jQuery.easing,{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	}
});

// a cheap path checker ripped off from http://devkick.com/lab/path/
// for compatibility
// turn a relative url into an absolute url
String.prototype.absUrl = function() {
	var l = window.location, h, p, f, i;
	if (/^\w+:/.test(this)) {
		return this.toString();
	}
	h = l.protocol + '//' + l.host;
	if (this.indexOf('/') === 0) {
		return h + this.toString();
	}
	p = l.pathname.replace(/\/[^\/]*$/, '');
	f = this.match(/\.\.\//g);
	if (f) {
		var n = this.substring(f.length * 3);
		for (i = f.length; i--;) {
			p = p.substring(0, p.lastIndexOf('/'));
		}
	} else {
		n = this.toString();
	}
	return h + p + '/' + n;
};
// compare two arrays to see if they are similar
Array.prototype.compare = function(t) {
	if (this.length != t.length) { return false; }
	for (var i = 0; i < t.length; i++) {
		if (this[i] !== t[i]) { 
			return false;
		}
	}
	return true;
};
// remove trailing slashes
String.prototype.noSlash = function() {
	return this.lastIndexOf('/') === this.length-1 ? this.substr(0,this.length-1) : this.toString();
};
// get the window's url
function windowUrl(address) {

	// define window.location as a short variable
	var _l = window.location;
	
	if (_l.hash.length > 0){
	  // var _h = _l.hash.split("#")[1]
	  // var _h
	}
	//var _h = $.address.value();
	// grab the window path, split & and parse
  // var _w = (_l.protocol + '//' + _l.hostname + _l.pathname + _l.hash).split('/');
  var _w = (_l.protocol + '//' + _l.hostname + address).split('/');
	
	// grab the query string, split & sort if not in strict mode
	//var _q = _l.search.substring(1).length > 0 ? _l.search.substring(1).split('&') : [];
	//if (!$.path.strictQuery) { _q.sort(); }
	
	// merge the arrays
	return _w;//.concat(_q);
}

function bumpOut(){
  // if page not docroot, then bump to this hashpage
  var p = window.location.pathname;
  var h = window.location.href.split("?");
  if(p != "/"){ 
    if (h.length < 2){ window.location = "/#"+p;} // no querystring
    else{ window.location = "/#"+p+"?"+h[1]; }    // add qs to location
    
  }  
}

function buildGallery(){
  $("ul.gallery li:eq(0)").addClass("active");
  $("ul.gallery li").css({width:"75px", height:"75px",overflow:"hidden",display:"inline-block"});
  $("ul.gallery li img").css({height:"100%", width:"auto", cursor:"pointer"}).
    click(function(evt){
      if($("#maingallery *").length > 0){
        // console.debug("found something inside gallery!")
        var that= this;
        $("#maingallery img").fadeOut(350,function(){
          $("#maingallery").empty();
          $(that).clone().css({"display":'none'}).delay(80).appendTo("#maingallery").fadeIn(350);
          $("<p class='attr'>").text($("#maingallery img").attr("title")).appendTo("#maingallery");
        });
      }else{
        $(this).clone().css({"display":'none'}).delay(0).appendTo("#maingallery").fadeIn(350);
        $("<p class='attr'>").text($("#maingallery img").attr("title")).appendTo("#maingallery");
      }
      
    });
    $("ul.gallery li.active img").clone().css({"display":'none'}).delay(0).appendTo("#maingallery").fadeIn(350);
    $("<p class='attr'>").text($("#maingallery img").attr("title")).appendTo("#maingallery");
    
}

function xhrLoader(response, status, xhr){
  // handle 404 pages
  if (xhr.status == "404"){
    $("#pagebody").html(response);
  }
  if (xhr.status == "503"){
    // there was an error loading the page (usually tumblr), try reloading in ~1s
    var tryAgain = function(dest){
      $("#pagebody").load(""+$.address.value(),xhrLoader);
    };
    $("#pagebody").html(response);
    window.setTimeout(tryAgain,900); // this should do something more logarithmic
  }
  // reset page title when navigating
  var pagetitle = $("article").attr("rel");
  if(pagetitle && pagetitle.length > 0){
    $.address.title("She & Him ☁ " + pagetitle);
  }else{
    $.address.title("She ☁ Him ");
  }
  
  // update the type
  Cufon.refresh();  
  
  // fade page in
  $("#pagebody").fadeIn(350).css({display:"block"}); 
  $("a[rel]",this).address(); // make links with rels deep links
  
  // enable addthis button on every page
  addthis.button(".addthis_button");
  
  $(".lyricslist").localScroll({
    target:".lyricsmask",
    axis:"xy",
    hash:false,
    duration:550,
    easing:"easeInOutCubic"
  });
  
  // $.address() handling for specific pages
  var root = $.address.pathNames()[0];
  if(root == "photos"){
    // build gallery here
    buildGallery();
  }
}

function activateNav(){
  // make specific links active depending on url
  var w_url = windowUrl($.address.value().noSlash());
  $("nav a").each(function(i,v){
    var a_url = $(this).attr("href").absUrl().noSlash().split("/");
    
    $(this).parent().parent().removeClass("active");
    $(this).parent().removeClass("active");
    		
    if(w_url.length >= a_url.length && 
        w_url.slice(0,a_url.length).compare(a_url)){
      $(this).parent().addClass("active");
      $(this).parent().parent().addClass("active");
    };
  });
}

function setupAudioPlayer(){
  // for the music player
  
  // text that gets changed (for hiding/showing)
  var playerText = '.listen h4,.listen p.trackname,.listen a.pause,.listen a.next';
  var playing = false;
  
  var track = 0;
  var tracks = [
{name:"In the Sun", album:"Volume Two", url:"/music/inthesun.mp3"},
   
    {name:"Why Do You Let Me Stay Here?", album:"Volume One", url:"/music/she_and_him_why.mp3"}
    ];
  
  
  // css hover breaks with it being opacity 1 by default, so...
  $('.listen').hover(function(){
  	if(playing) {
  		$(playerText).css('opacity',1);
  	}
  },function(){
 	if(playing) {
  		$(playerText).css('opacity',0);  		
  	}
  });
  
  $("#audioplayer").jPlayer({
    ready:function(){
      $(this).setFile(tracks[track % tracks.length].url);
    },
    swfPath:"/scripts/"
  }).onProgressChange(function(){}).
  onSoundComplete(function(){
    track += 1;
    var ct = tracks[track % tracks.length];
    
    // console.debug("track:", ct);
    $(".listen h4").html(ct["album"]);
    $(".listen .trackname").text(ct["name"]);
    Cufon.refresh();
    
    $(this).setFile(ct["url"]).play();
    $(".listen").addClass("stop");

	$(playerText).css('opacity','1');    
	setTimeout( function() { $(playerText).css('opacity','0'); }, 6000);
  });
  
  $(".listen a.next").click(function(){
    track += 1;
    var ct = tracks[track % tracks.length];
    
    // console.debug("track:", ct);
    $(".listen h4").html(ct["album"]);
    $(".listen .trackname").text(ct["name"]);
    Cufon.refresh();
    
    $("#audioplayer").setFile(ct["url"]).play();
    $(".listen").addClass("stop");
    
	setTimeout( function() { $(playerText).css('opacity','0'); }, 6000);

  });

  $(".listen a.pause").toggle(function(){
  	playing = false;
    $("#audioplayer").pause();
    $(".listen").removeClass("stop");
    
	$(playerText).css('opacity','1');

    
  },function(){
    playing = true;
    $("#audioplayer").play();
    $(".listen").addClass("stop");

	$(playerText).css('opacity','0');
    
  });
  
  // make the audio player toggle correctly
  $(".listen a.play").toggle(function(evt){
    playing = true;
    $(".listen a.play").addClass("stop");
    $(".listen").addClass("stop");
    $("#audioplayer").play();
    
    $(playerText).css('opacity','0');
   
    //var nt = tracks[ (track+1)%tracks.length ];
	//$("#playing-next-title").text(nt["name"]);
	//$("#playing-next").show();

  },function(evt){
    $(".listen a.play").removeClass("stop");
    $(".listen").removeClass("stop");
    playing = false;
    $("#audioplayer").pause();
    
    $(playerText).css('opacity','1');

    $("#playing-next").hide();
  });
}

function loadPage(){
  // bump out of subpages to hashpages
  bumpOut();
  
  if($.address.value() == "/" && showSplash){
    // redirect to splash if showSplash set
    $.address.value("/splash");
  }
  else if($.address.value() == "/" && !showSplash){
    // hide nav, header before loading content
    $("nav li:eq(0)").fadeIn();  // on homepage, hide nav
    $("nav li:gt(0), header").hide(0); // hide header (yellow band)
    $("nav").css({"z-index":50});  // promote the player to top of page
    $("body").addClass("splash"); // grid the body
    $("#pagebody").hide(0).load(""+$.address.value(),xhrLoader);
  }
  else if($.address.value() == "/splash"){ // if visiting the splash page
    showSplash = false;
    $("body").removeClass("splash");
    $("nav li, header").hide(0);
    $("#pagebody").hide(0).load(""+$.address.value(),xhrLoader);
  }else{
    $("body").removeClass("splash"); // if visiting any other page
    $("nav li, header").show(0);
    $("#pagebody").hide(0).load(""+$.address.value(),xhrLoader);
  }
  
  // make root links active
  activateNav();
}


function makeCloud(cloud_no,offsetTop,someDelay){
  var time = 1000 * 60 * 2 + 1000 * 30 * Math.ceil(Math.random() * 6); // + Math.random() * 0.8 * 60 * 2000;
  var top_pos = offsetTop + 50 * Math.random();
  var left_pos = -1000 + Math.ceil(Math.random() * 400);
  var vertMovement = -10 + Math.ceil(Math.random() * 10); //-400 + Math.ceil(Math.random() * 600);
  var vertOffset = (vertMovement >= 0) ? "+="+vertMovement : "-="+Math.abs(vertMovement);
  var cloud_src = "/images/cloud_"+cloud_no+".png";
  var cloud = $("<div />").
    css({position:"absolute", "top":top_pos, "left":"-370px"}).
    delay(someDelay).html("<img src='"+cloud_src+"'>").prependTo("#cloudHolder");
  cloud.animate({left:"+=2000px",top:vertOffset}, time, "linear", function(){
    $(this).remove();
    makeCloud(cloud_no,offsetTop,someDelay);
  });  
}

$(document).ready(function(){
  makeCloud(1,100,500);
  makeCloud(2,275,68000);
  makeCloud(3,400,41000);

  try{showSplash = showSplash;}catch(e){showSplash = false;}
  $.address.change(loadPage);
  
  setupAudioPlayer();
});
  

