// prevent firebug console.log statements from breaking IE
if( window.console == undefined ) { window.console = { log: function(){} }; }

var j = window.j = jQuery;
var em = window.em = new Empire();
var er = window.er = new Error();

function Empire() {
   if ( !(this instanceof arguments.callee) )
      return new Empire();
};

function Error() {
   if ( !(this instanceof arguments.callee) )
      return new Error();
};

j(document).ready( function() {
   em.init();
   em.select_photo();
   em.sliding();
   em.show_blog();
   em.glat();
   em.update_orientation();

   em.detect_redirect();

   // j("body").unbind().bind( "onorientationchange", em.update_orientation );
} );


// If url specifies id, and hash has different id, 
// redirect to id specified in hash

Empire.prototype.detect_redirect = function() {
  
   if( window.location.toString().indexOf( "/blogs" ) ) {
      redirect_blog();
      return;
   }
   redirect_photo();
};

function redirect_blog() {
   var hash = window.location.hash.substring(1);

   if( hash.length == 0 )
      return false;
   
   var el;
   
   if( hash.match( /^\d+$/ ) ) {
      el = j( "#id" + hash );
   }
   else {
      el = j( "a[name=" + hash + "]" ).parent();
   }

   if( el.length == 0 )
      return false;

  el.find( "a.more:first" )
    .click();
}

function redirect_photo() {
   var hash = window.location.hash;
   if( hash.substr(1, 2) == "id" ) {
      var url = window.location.href;
      var new_id = hash.substr(3);
      
      url = url.replace( /\/id\/\d+\//, "/id/" + new_id + "/" );
      url = url.replace( /#.+/, "" );
      
      window.location.href = url;
   }
   else if( hash.length > 0 ) {
      // Hash exists, but not recognized.  Remove
      window.location.hash = "";
   }
}

Empire.prototype.glat = function() {
//   j.getJSON( "http://www.google.com/latitude/apps/badge/api?user=2133685568483210142&type=json", function( data ) {
//      console.log( data );
//   } );
}

Empire.prototype.init = function() {

   j.getJSON("/status", function( data ) {

      //var html5_audio = data.f_message.length <= 100 ? '<br /><audio controls width="30" src="http://translate.google.com/translate_tts?q=' + data.f_message + '%20" />' : '';
      j(".fb_status")
      //.find(".statii").html( data.f_message + html5_audio )
      .find(".statii").html( data.f_message )
      .parent().find(".time_since").html( "posted " + data.time_since + " " + data.source );

      // Reduce font size if text uses more than 2 lines
      var height = j(".statii").height();
      if( height >= 174 ) {
         j(".statii").addClass("over2lines");
      }
   } );

	// console.log( "HERE:" + j("pre[name=code]:visible") );
	if( j("pre[name=code]:visible").length > 0 ) {
		dp.SyntaxHighlighter.ClipboardSwf = "/static/js/sh/clipboard.swf";
		dp.SyntaxHighlighter.HighlightAll( "code" );
	}
   //   j("#header .load[content=status]").load( "_status.html" );

   //j("#photosets .photo").each( function() {
   //   var el = j(this);
   //   if( el.hasClass("january") )
   //      el.
   //} );
};

function slide_el( container, direction, new_el ) {
   
   container.effect( "slide", { direction: direction.shift(), mode: "hide" }, 150, function() { 
      new_el.effect( "slide", { direction: direction.shift(), mode: "show" }, 150 );
      setTimeout( function() { window.location.hash = new_el.attr("id"); }, 1000 );
   } );
}

function cache_el( id, url, container, callback ) {
   
   // Check for cached photo
   var cache = j( "#" + id );
   if( cache.length > 0 ) {
      if( j.isFunction( callback ) ) {
         callback();
      }
      return false;
   }
    
   var in_process = j("body").data( url );
   if( in_process ) {
      return false;
   }
   
   j("body").data( url, true );
   
   // Photo not cached, retrieve
   var div = j.get( url, function( data ) {
      
      // Copy events and append new photo
      var new_el = j( data ).hide();
      new_el.copyEvents( container );
      container.parent().append( new_el );
      j("body").removeData( url );

      if( j.isFunction( callback ) ) {
         callback();
      }
   } );
}

Empire.prototype.sliding = function() {

   j("#content > .slide")
   .unbind( "mouseover" )
   .mouseover( function( ev ) {
      var container = j(this);
      var el = j( ev.target );
      
      // Include images with a.href parents
      el = el.parents("a").andSelf();
      
      if( el.hasClass("next") || el.hasClass("previous") ) {
         var id = el.metadata().id;
         if( id && id.length > 0 ) {
            cache_el( id, el.attr("href"), container );
         }
      }
   } );

   j("#content > .slide")
   .unbind( "click" )
   .click( function( ev ) {
      var container = j(this);
      var el = j( ev.target );
      
      // Include images with a.href parents
      el = el.parents("a").andSelf();
      
      if( el.hasClass("next") || el.hasClass("previous") ) {
         // Replace #photo with new #photo, copying events and sliding in appropriate direction

         // var direction = el.hasClass("previous") ? [ "left", "right" ] : [ "right", "left" ];
         var direction = el.hasClass("previous") ? [ "right", "left" ] : [ "left", "right" ];
         
         var id = el.metadata().id;
         cache_el( id, el.attr("href"), container, function() {
            slide_el( container, direction, j("#" + id) );
            return false;
         } );
         
			return false;
      }
   } );
};

Empire.prototype.select_photo = function() {
   
   return false;
   
   j(".photoset")
   .unbind( "click" )
   .click( function( ev ) {
      
      if( ev.target.nodeName == "IMG" ) {

         var img = j(ev.target);
         var image_url = img.parent("a").attr("href");
        
         img.attr("src", image_url);

         return false;
      }
   } );
};

Empire.prototype.update_orientation = function() {
   
   var width;
   switch( parseInt( window.orientation ) ) {
      case 0:
         // portrait mode
         width = 430;
         this.iphone_vertical();
         break;
      case -90:
         // landscape mode
         width = 280;
         this.iphone_horizontal();
         break;
      case 90:
         // landscape mode
         width = 280;
         this.iphone_horizontal();
         break;
   } 

//   alert( j("#google-calendar iframe").css( "width" ) );
   var iframe = j("#google-calendar iframe");
   if( iframe.length > 0 ) {
      iframe.css( { width: width + "px" } );
      iframe[0].window.location.reload();
   }
};

Empire.prototype.iphone_vertical = function() {
   j( ".photos.mini-thumbnails.home" ).removeClass( "horizontal" );
};

Empire.prototype.iphone_horizontal = function() {
   j( ".photos.mini-thumbnails.home" ).addClass( "horizontal" );
};


Empire.prototype.show_blog = function() {

   j( "#blogs" )
   .unbind( "click" )
   .click( function( ev ) {
      
      // container
      var cnr = j( this );
      
      var el = j( ev.target );
      
      if( el.hasClass( "more" ) ) {

         var li = el.parents( ".blog" );
         var blog_id = li.attr( "id" );
			var single = j( "#" + blog_id + ".single" );
 
			// Whole blog entry already in DOM
         if( single.length > 0 ) {
            // Hide list and show single
            single.removeClass( "hidden" );
            li.addClass( "hidden" );
            //window.location.hash = "#" + blog_id;
         }
         else {
            // Get single blog entry
            j.get( el.attr( "href" ), function( xhr ) {
               // Add single blog entry
               // Hide list entry
               var li = j( xhr ).find( "li.blog" );
               el.parents( ".blog" )
               .before( li )
               .addClass( "hidden" );

               // li.effect( "highlight", {}, 10000 );
               li.addClass( "highlighted" );
               dp.SyntaxHighlighter.HighlightAll( "code" );
               j( "pre" ).removeAttr( "name" );
               //window.location.hash = "#" + blog_id;
            } );
         }

         return false;
      }
      else if( el.hasClass( "less" ) ) {
     
         var blog = el.parents( "li.blog" );
         var blog_id = blog.attr( "id" );
         var container = blog.parent();
         console.log(  "." + blog_id + ".single" );
         console.log( container.children( "." + blog_id + ".single" ) );

         if( container.find( "." + blog_id + ".single" ).length > 0 ) {
            // Show list blog

            cnr.find( "#" + blog_id + ".blog.hidden" ).removeClass( "hidden" ).effect( "highlight", {}, 2000 );
                 
            // Hide single blog
            cnr.find( "#" + blog_id + ".blog.single" ).addClass( "hidden" );
         }
         else {

            j.get( el.attr( "href" ), function( xhr ) {
                    
               // Show list blog
               cnr.find( "#" + blog_id + ".blog.hidden" ).removeClass( "hidden" ).effect( "highlight", {}, 2000 );
                    
               // Hide single blog
               cnr.find( "#" + blog_id + ".blog.single" ).addClass( "hidden" );

            } ); 
         }    
         window.location.hash = "#" + blog_id;
         
         return false;
      }
   
   } );
};
