/* Author: mediaBOOM

*/

if(!Array.indexOf){
	    Array.prototype.indexOf = function(obj){
	        for(var i=0; i<this.length; i++){
	            if(this[i]==obj){
	                return i;
	            }
	        }
	        return -1;
	    }
	}

$(document).ready(function() {

	/********* FUNCTION DEFINITIONS **********/
	
	function navigateTo(page) {
		if(page == "#") return;
		var mainContent = $('#right');
    var sketches = $('#right_sketches, #right_still_sketches');
    //var still_sketches = $('#right_still_sketches');
		// prep body class
		newBodyClass = getBodyClassFromFile(page);
    newSecondaryBodyClass = getSecondaryBodyClassFromFile(page);
		
		// update the title tag
    var page_name = (newSecondaryBodyClass ? page_titles[newSecondaryBodyClass] : page_titles[newBodyClass])
		document.title = page_name + " - Homer Liwag";
    $('h1').eq(0).html(page_name);
		
		// fade out the main content
    function out_anim() {
      var options = {};
      if($('body').hasClass('about') || $('body').hasClass('contact')) {
        options.left = "-" + $('#paper').width();
      } else {
        options.opacity = "0";
      }
      options.useTranslate3d = isIOS;
      return options;
    }
    
    function in_anim() {
      var options = {};
      if(newBodyClass == "about" || newBodyClass == "contact") {
        mainContent.css('left', "-" + $('#paper').css('width')).css('opacity', "1");
        options.left = "0";
      } else {
        mainContent.css('left', "0").css('opacity', "0");
        options.opacity = "1";
      }
      options.useTranslate3d = isIOS;
      return options;
    }
    
		mainContent.animate(out_anim(), 200, function() {
      mainContent.css('display', 'none');
      $('#spinner').css('display','block').animate({opacity: 1, useTranslate3d: isIOS}, 200);
      $.get(page + "?ajax=1",
        function(data) {
          if($('body').hasClass(newBodyClass)) {
            // same section (i.e., from one "still" subpage to another "still" subpage)
            $('body').removeClass().addClass(newBodyClass).addClass(newSecondaryBodyClass);
            $('#spinner').animate({opacity: 0, useTranslate3d: isIOS}, 200, function () {
              $(this).css('display','none');
              mainContent.css('display', 'block').html(data);
              if(newBodyClass == "still" || newBodyClass == "portfolio" || (newBodyClass == "reel" && $('html').hasClass('touch')) || (newBodyClass == "motion" && $('html').hasClass('touch')))  {
                mainContent.css('left', "0").css('opacity', "1");
              } else {
                mainContent.animate(in_anim(), 200);
              }
              initializePage();
            });
          } else {
            // different section
            sketches.animate({opacity: 0, useTranslate3d: isIOS}, 200, function () {
              $(this).css('display','none');
              $('body').removeClass().addClass(newBodyClass).addClass(newSecondaryBodyClass);
              $('#spinner').animate({opacity: 0, useTranslate3d: isIOS}, 200, function () {
                $(this).css('display','none');
                sketches.css('display','block').animate({opacity: 1, useTranslate3d: isIOS}, 200, function() {
                  mainContent.css('display', 'block').html(data);
                  if(newBodyClass == "still" || newBodyClass == "portfolio" || (newBodyClass == "reel" && $('html').hasClass('touch')) || (newBodyClass == "motion" && $('html').hasClass('touch')))  {
                    mainContent.css('left', "0").css('opacity', "1");
                  } else {
                    mainContent.animate(in_anim(), 200);
                  }
                  initializePage();
                });
              });
            });
          }
        }
      );
    });
	}
	
	function getFragmentFromFile(filename) {
		return("#"+filename.split('.')[0]);
	}
	
	function getFileFromFragment(fragment) {
		return(fragment.split('#')[1] + ".php")
	}

	function getBodyClassFromFile(filename) {
		var retval = filename.split('.')[0].split('-')[0].replace('_','-');
		retval = (retval == "index") ? "home" : retval;
		return retval;
	}
  
  function getSecondaryBodyClassFromFile(filename) {
    var retval = filename.split('.')[0];
    retval = (retval.substring(0,5) == "still") ? retval : "";
    return retval;
  }

	function initializePage() {
  
    // inserts correct width for all media galleries (reel, motion, still, and portfolio)
    if($('body').hasClass('still') || $('body').hasClass('reel') || $('body').hasClass('motion') || $('body').hasClass('portfolio')) {
      $('#gallery').css('width', gallery_width);
      if($('html').hasClass('touch')) {
        myScroll = new iScroll('scroller');
      }
    }
    
    // reel and motion pages
    if($('html').hasClass('no-touch') && ($('body').hasClass('reel') || $('body').hasClass('motion'))) {
        $('iframe').each(function(){
          $f(this).addEvent('ready', ready);
          function ready(player_id){
            $('#'+player_id).animate({opacity: 1, useTranslate3d: isIOS}, 500);
          }
        });
    }
    
    // still and portfolio pages
    if($('body').hasClass('still') || $('body').hasClass('portfolio')) {
      /* $("#gallery li").each(function(index,el){
        var img = new Image();
        $(img).load(function () {
            $(el).append(this);
            $(this).animate({opacity: 1, useTranslate3d: isIOS}, 500);
        }).error(function () {
          $(el).remove();
        }).attr('src', 'flickr_assets/' + set_dir + '/' + images[index]);
      }); */
      
      var items = $("#gallery li");
      function load_sequentially(index) {
        var item = items.eq(index);
        var img = new Image();
        $(img).load(function () {
          $(item).append(this);
          $(this).animate({opacity: 1, useTranslate3d: isIOS}, 500);
          if(index+1 < images.length) {
            load_sequentially(index+1);
          }
        }).attr('src', 'flickr_assets/' + set_dir + '/' + images[index]);
      }
      load_sequentially(0);

      
    }
  
    // home page
    if($('body').hasClass('home')) {
      var home_preload = ["photo_grid_color.jpg", "photo_grid_bw.jpg"];    
      var imgNum = home_preload.length;
      var home_grid = $("#home_grid");
      var home_grid_items = $("#home_grid li");
      $('body').addClass('loading');
      $.each(home_preload, function(index, value) { 
        var img = new Image();
        $(img).load(function () {
            if(!--imgNum) {
              $('body').removeClass('loading');
              home_grid.animate({opacity: 1, useTranslate3d: isIOS}, 200);
            }
        }).attr('src', 'img/'+value);
      });
		}
    
    // about page
    if($('body').hasClass('about')) {
      $('#scroll-pane').jScrollPane({showArrows: true});
		}

    // update page
    if($('body').hasClass('update')) {
      $('#update_site_button').click(function (el) {
        $(this).not(":animated").fadeOut(100, function() {
          $('#updating').fadeIn(100, function() {
            $.get('update-script.php', function(data) {
              $('#updating').fadeOut(100, function() {
                $('#update_site_button').fadeIn(100);
              });
            });
          });
        });
        return false;
      });
		}
      
		
	}
	
	/********* IMMEDIATELY EXECUTING CODE **********/	
	
  // preload various images
  var preload = ["paper_edge.gif", "subnav_shadow.png","subnav.jpg"
               ,  "contact_bg.jpg", "contact_social.jpg", "contact_copy.png", "scroller-line.png", "scroller-mid.png", "scroller-arrow-top.png", "scroller-arrow-bottom.png"
               , "about_bg.jpg", "about_copy.png", "about_tape.jpg"
               , "reel_sketches.png"
               , "still_sketches.png"
               , "motion_sketches.png"
               , "portfolio_sketches.png"
               ];    
  $.each(preload, function(index, value) { 
    var img = new Image();
    $(img).load().attr('src', 'img/'+value);
  });
  
  // for touch devices to show/hide subnav (CSS hover rules work fine for non-touch devices)
  var nav_btn_still_span = $('html.touch #nav .still span');
  var subnav_still_outer = $('html.touch #subnav_still_outer');
  
  nav_btn_still_span.mouseover(function() {
    subnav_still_outer.css('display', 'block');
  });
  
  $('#subnav_still li').click(function() {
    subnav_still_outer.css('display', 'none');
  });
  
  var isIOS = navigator.userAgent.match(/iPhone/i) !== null || navigator.userAgent.match(/iPad/i) !== null;
  // ajaxify links sitewide for IE8 and above
  if(!isIOS && !($.browser.msie && ($.browser.version == "7.0" || $.browser.version == "6.0"))) {
    $('a:not(#update_site_button)').live('click',function(){
			var target = $(this).attr('href');
			if(	(target.slice(0,4) == "http") || 
					(target.indexOf('@') != '-1') || 
					(target.substr(target.length - 4, 4) == ".pdf" )
			) return true;	// offsite / email  / pdf links
			// update the URL and trigger navigation event
			window.location.hash = getFragmentFromFile($(this).attr('href'));
			return false;
		});
	}

  // on desktops, reposition certain elements on resize or scroll
  if($('html').hasClass('no-touch')) {
    var repositioned = $("#left,#right_sketches, #right_still_sketches, #right_bg, #right_shadow_left, #right_shadow_top, #right_shadow_bottom");
    var footer = $('footer');
    didScroll = didResize = false;
    $(window).scroll(function() {
        didScroll = true;
    });
    $(window).resize(function() {
      didResize = true;
    });
    setInterval(function() {
      if ( didScroll || didResize ) {
        didScroll = didResize = false;
        if($('html').height() <= 744) {
          repositioned.css('top', (Math.max(0,($('html').height() - 699)/2 - 23) - $(window).scrollTop()) + 'px');
          footer.css('top', (Math.max(0,($('html').height() - 699)/2 - 23) - $(window).scrollTop() + 699) + 'px');
        } else {
          repositioned.css('top', 'auto');
          footer.css('top', 'auto');
        }
          
      }
    }, 5);
  }
  
	// handle deeplinking
	var curHash = document.location.hash;
	var bodyClass;
	var loc = document.location.href;
	var filename = loc.split('/')[loc.split('/').length - 1].split('#')[0];
	filename = filename ? filename : "index.php";		// handle home page
	if(curHash) {
		
		bodyClass = getBodyClassFromFile(filename);
		curHash = getFragmentFromFile(filename);
	} else {
		curHash = getFragmentFromFile(filename);
		document.location.hash = curHash;
		bodyClass = getBodyClassFromFile(filename);
	}
	
	setInterval(checkLocation, 100);
	
	function checkLocation() {
		var newHash = document.location.hash;
		if(curHash != newHash) {
			navigateTo(newHash.split('#')[1] + '.php');
			curHash = newHash;
		}
	}	
  
	initializePage();	
	
});














