UTIL = {
  fire : function(func,funcname, args){
    var namespace = core;
 
    funcname = (funcname === undefined) ? 'init' : funcname;
    if (func !== '' && namespace[func] && typeof namespace[func][funcname] == 'function'){
      namespace[func][funcname](args);
    } 
  }, 
 
  loadEvents : function(){
    var bodyId = document.body.id;
    // hit up common first.
    UTIL.fire('common');
    // do all the classes too.
    $.each(document.body.className.split(/\s+/),function(i,classnm){
      UTIL.fire(classnm);
      UTIL.fire(classnm,bodyId);
    });
    UTIL.fire('common','finalize');
  } 
};


randomHP = function(){
  var totalHP = 3;
  var rndNum = Math.floor(Math.random() * totalHP)+1;
  var path = '/_assets/images/home/greenwich_hotel-homepage-0'+rndNum+'.jpg';
  return path;
}

echo = function(txt, which){
	try{
		switch(true){
			case which == 'info':
				console.info(txt);
				break;
			case which == 'warn':
				console.warn(txt);
				break;
			case which == 'trace':
				console.trace();
				break;
			default:
				console.log(txt);
				break;
		}
	}
	catch(e){}
}

var vars = {};
var courtyardflash = ''+
	'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '+
	'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" '+
	'id="_assets/images/quotes/courtyard" '+
	'align="middle" height="120" width="474">'+
	'<param name="allowScriptAccess" value="sameDomain">'+
	'<param name="allowFullScreen" value="false">'+
	'<param name="wmode" value="transparent">'+
	'<param name="movie" '+
	'value="../_assets/images/quotes/courtyard.swf"><param '+
	'name="quality" value="high"><embed '+
	'src="../_assets/images/quotes/courtyard.swf" '+
	'quality="high" '+
	'name="_assets/images/quotes/courtyard" '+
	'allowscriptaccess="sameDomain" allowfullscreen="false" '+
	'type="application/x-shockwave-flash" '+
	'pluginspage="http://www.macromedia.com/go/getflashplayer" '+
	'align="middle" height="120" width="474" wmode="transparent">'+
	'</object>';

var drawingflash = ''+
	'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '+
	'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" '+
	'id="_assets/images/quotes/drawing" '+
	'align="middle" height="120" width="474">'+
	'<param name="allowScriptAccess" value="sameDomain">'+
	'<param name="allowFullScreen" value="false">'+
	'<param name="wmode" value="transparent">'+
	'<param name="movie" '+
	'value="../_assets/images/quotes/drawing.swf"><param '+
	'name="quality" value="high"><embed '+
	'src="../_assets/images/quotes/drawing.swf" '+
	'quality="high" '+
	'name="_assets/images/quotes/drawing" '+
	'allowscriptaccess="sameDomain" allowfullscreen="false" '+
	'type="application/x-shockwave-flash" '+
	'pluginspage="http://www.macromedia.com/go/getflashplayer" '+
	'align="middle" height="120" width="474" wmode="transparent">'+
	'</object>';

var homeflash = ''+
	'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '+
	'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" '+
	'id="_assets/images/quotes/home" '+
	'align="middle" height="120" width="474">'+
	'<param name="allowScriptAccess" value="sameDomain">'+
	'<param name="allowFullScreen" value="false">'+
	'<param name="wmode" value="transparent">'+
	'<param name="movie" '+
	'value="../_assets/images/quotes/home.swf"><param '+
	'name="quality" value="high"><embed '+
	'src="../_assets/images/quotes/home.swf" '+
	'quality="high" '+
	'name="_assets/images/quotes/home" '+
	'allowscriptaccess="sameDomain" allowfullscreen="false" '+
	'type="application/x-shockwave-flash" '+
	'pluginspage="http://www.macromedia.com/go/getflashplayer" '+
	'align="middle" height="120" width="474" wmode="transparent">'+
	'</object>';

set_winsize = function(){
	echo('set_winsize','info');
	vars.jqphotos_size = {
		w : vars.jqphotos.innerWidth(),
		h : vars.jqphotos.innerHeight()
	};
	if( $('body').hasClass('with-thirdtier-nav') ){
		vars.jqphotos_size = {
			w : vars.jqphotos_size.w-370,
			h : vars.jqphotos_size.h-370
		};
	}
}

get_size = function( imgWidth, imgHeight, toWidth, toHeight){
	echo( 'get_size : '+imgWidth+', '+imgHeight+', '+toWidth+', '+toHeight,'info');
	
	if (toHeight < toWidth) {
		//if (imgWidth > toWidth) {
			newWidth = toWidth;
			newHeight = imgHeight*(toWidth/imgWidth);
		//}
	}
	else {
		//if (imgHeight > toHeight) {
			newHeight = toHeight;
			newWidth = imgWidth*(toHeight/imgHeight);
		//}
	}
	return {w:newWidth,h:newHeight};
}

set_size = function(){
	echo('set_size','info');
	set_winsize();

	vars.photos = $('img', vars.jqphotos)
	.each(function(){
		var dem = get_size( this.width, this.height, vars.jqphotos_size.w, vars.jqphotos_size.h );
		$(this)
		.width( dem.w )
		.height( dem.h )
		.data('h', this.height)
		.data('w', this.width);
	})
	.eq(0)
	.fadeIn(900);
};
var zindex = 3000;
var pageload  = function( hash ){
	echo('start : pageload('+hash+')', 'info');
	if(hash) {
		echo('set_size : has hash','info');
		try{
			var pageTracker = _gat._getTracker("UA-17671580-1");
			pageTracker._trackPageview('/'+hash);
		}catch(e){echo(e);}
		$.ajax({
			dataType : 'html',
			url : hash,
			success : function( data, textStatus ){
				var photos 	= $('#photos img', data);
				var text 		= $('#main', data).html();
				var navgallery = $('#nav-gallery', data);
				var floorplan  = $('.floorplan a', data);
				
				$('#main').hide();
				
				if( !$('body').hasClass('has-navgallery') ){
					$('body').addClass('has-navgallery');
					navgallery = navgallery.appendTo( 'body' );
					curImage = 0;
				}
				else{
					navgallery = $('#nav-gallery');
					curImage = 0;
				}
				
				
				$('#snavCol')
					.animate({width:5}, 500,'easeInQuad',function(){});
				
				$('body').addClass('with-thirdtier-nav');

				if( !$('#contentCol').hasClass('out') ){
					$('#contentCol')
						.addClass('out')
						.width(0)
						.animate({'width':240}, 400, 'easeInOutCirc');
						
						afterload(text);
						
						$('.nav', '#contentCol .gut')
						.appendTo( $('#contentCol') )
						.addClass('nav-rooms-to-remove');
				}
				else{
					afterload(text);
				}
				
				function afterload( text ){
					
					echo('start : afterload');
					
					set_winsize();
					
					$('img', vars.jqphotos).addClass('old');
					
					vars.photos = $(photos);
					
					vars.photos.eq(0).data('first',true);
					
					vars.photos
					.prependTo( vars.jqphotos )
					.addClass('nne')
					.onImagesLoad({
						itemCallback : function( el ){
							var i = $(photos).index(el);
							zindex = zindex- i;
							var dem = get_size( el.width, 
										    el.height, 
										    vars.jqphotos_size.w, 
										    vars.jqphotos_size.h );
							echo('point 1');
							$(el)
							.removeAttr('alt')
							.width( dem.w )
							.height( dem.h )
							.css('z-index',zindex)
							.data('h', el.height)
							.data('w', el.width)
							.hide()
							.removeClass('nne');
							
							if( $(el).data('first') ){
								$('body, #nav-tier2 a, #nav-rooms a').css('cursor','');
								
								$(el)
								.fadeIn(400)
								.siblings('.old')
								.fadeOut(400, function(){
									$(this).remove();
								});

								$('#contentCol .gut')
								.fadeOut(200, function(){
									$(this).html( text ).fadeIn(300);
									
									$('.nav-rooms-to-remove').remove();
									
									$('.nav', this)
									.appendTo( $('#contentCol') )
									.addClass('nav-rooms-to-remove');
									
								});
							}
						}
					})/*
					.parent()
						.children(':not(.old)')
						.removeClass('nne')
						.end()
						.children(':not(.old)');*/

					if( vars.photos.size() > 1 ){
						navgallery.show();
					}
					else{
						navgallery.hide();
					}

					var lastRef = null;
					var doFloorPlan = false;
					
					$('.gut .floorplan a')
					.live('click',function(){
							echo('.gut .floorplan a LOAD');
						navgallery.find('.next a').data('doFloorPlan',true).trigger('click');
						return false;
					});
					
					curImage = 0;
					firstLoad = true;
					
					navgallery
					.find('a')
					.unbind('click')
					.click(function(){				
						if( firstLoad ){
							vars.photos = $('#photos img:not(.old)');
							curImage = 0;
							firstLoad = false;
						}
						
						var el = $(this);
						if( el.parent().hasClass('prev') ){
							vars.photos.eq( curImage-- ).fadeOut(600);
							if (curImage == -1 ) {
								curImage = (vars.photos.size()-1);
							}
							vars.photos.eq( curImage ).fadeIn(600);
						}
						else{
							vars.photos.eq( curImage++ ).fadeOut(600);
							echo(el.data('doFloorPlan'));
							if( el.data('doFloorPlan') ){
							echo('doFloorPlan LOAD');
								curImage = vars.photos.size() - 1;
								el.data('doFloorPlan',false);
							}
							else if (curImage == (vars.photos.size()) && !doFloorPlan ) {
								curImage = 0;
							}
							vars.photos.eq( curImage ).fadeIn(600);
						}
						thislstcls = vars.photos.eq( curImage ).attr('ref');
						navgallery.removeClass(lastRef).addClass(thislstcls);
						lastRef = thislstcls;
						return false;
					});
					
					try{
						DD_belatedPNG.fix('#contentCol .gut h1 img');
					}catch(e){}
				}
			},
			error : function( XMLHttpRequest, textStatus, errorThrown ){
				echo(errorThrown, 'error');
			}
		});
	}
	else{
		echo('set_size : no hash','info');
		$('body').removeClass('with-thirdtier-nav');
		
		$('#snavCol').animate({width:155}, 500,'easeInQuad');
		$('#contentCol').removeClass('out').animate({'width':0}, 700, 'easeInOutCirc')
		
		$('img', vars.jqphotos).addClass('old');
		$('#nav-gallery').remove();
							
		$('body, #nav-tier2 a, #nav-rooms a').css('cursor','');

		vars.photos = $(vars.photosorg)
					.removeClass('old')
					.appendTo( vars.jqphotos )
					.parent()
						.children('.old')
						.fadeOut(400, function(){
							$(this).remove();
						})
						.end()
						.children(':not(.old)')
						.hide()
						.removeClass('nne')
						.end()
						.children(':not(.old):first')
						.fadeIn(400)
						.end()
						.children(':not(.old)');

		vars.photos = $('img', vars.jqphotos);
		set_size();
	}
}
var vars = {};
var core = {
	common : {
		init     : function(){
			echo('core -> common -> init','info');
			
			
			vars.jqphotos = $('#photos .holder');
			set_winsize();
			vars.photos = vars.photosorg = $('img', vars.jqphotos);
			
			vars.photos.eq(0).data('first',true);
			
			vars.photos
			.addClass('nne')
			.onImagesLoad({
				itemCallback : function( el ){

					var dem = get_size( 
								    el.width, 
								    el.height, 
								    vars.jqphotos_size.w, 
								    vars.jqphotos_size.h );
					
					$(el)
					.width( dem.w )
					.height( dem.h )
					.data('h', el.height)
					.data('w', el.width)
					.hide()
					.removeClass('nne');
					
					if( $(el).data('first') ){
						$(el).fadeIn();
					}

				}
			});
		},
		finalize : function(){
			echo('core -> common -> finalize','info');
			
			$('img[alt]').removeAttr('alt');	
			if( $.browser.msie && $.browser.version <= 8 ){
				$(window)
				.resize(function(){ 	
					$('body').removeClass('dummy').addClass('dummy');
				})
				$('#nav-rooms').css('top',-25);
			}

    		var resizeTimeout = null;
			$(window)
			.resize(function(){ 
				if (resizeTimeout) clearTimeout(resizeTimeout);
				
				echo('core -> common -> finalize -> .resize()','info');
				
				resizeTimeout = setTimeout(function(){
					vars.jqphotos_size = {
						w : vars.jqphotos.innerWidth(),
						h : vars.jqphotos.innerHeight()
					};
					
					if( $('body').hasClass('with-thirdtier-nav') ){
						vars.jqphotos_size = {
							w : vars.jqphotos_size.w-370,
							h : vars.jqphotos_size.h-370
						};
					}
					
					$('img', vars.jqphotos)
					.each(function(){
						var dem = get_size( this.width, this.height, vars.jqphotos_size.w, vars.jqphotos_size.h );
						$(this)
						.width( dem.w )
						.height( dem.h );
					});
				}, 100);
			});
		}
	},
	page : {
		room  : function(){
			echo('core -> page -> room','info');
			
			$('html').addClass('room');
			
			//set_size();
			
			// set up the history stuff
			$.historyInit(pageload, location.pathname);
			$("body").ajaxStart(function(){
				$(this).css('cursor','wait');
			});

			
			$('#nav-tier2 a, #nav-rooms a')
			.live('click',function(e){
				e.preventDefault();
				var path = this.pathname;//$(this).attr('href');
				$(this).css('cursor','wait');
				if( $.browser.msie ){
					path = '/'+ path;
				}
				
				$.historyLoad(path);
				return false;
			});
		},
		index : function(){
			echo('core -> page -> index','info');
			vars.randomHP = randomHP();
			vars.jqphotos = $('#photos .holder');
			vars.jqphotos_size = {
				w : vars.jqphotos.innerWidth(),
				h : vars.jqphotos.innerHeight()
			};
			
			if( $('body').hasClass('with-secondtier-nav') ){
				vars.jqphotos_size = {
					w : vars.jqphotos_size.w-370,
					h : vars.jqphotos_size.h-370
				};
			}
			
			var noCache = $.browser.msie ? '?t='+Math.round(new Date().getTime()/1000):'';
			var preview = new Image();
			
			preview.onload = function(){
				this.onload = null;
				var dem = get_size( this.width, this.height, vars.jqphotos_size.w, vars.jqphotos_size.h );
				vars.jqphotos_photo = $(this)
				.appendTo( vars.jqphotos )
				.width( dem.w )
				.height( dem.h )
				.data('h', this.height)
				.data('w', this.width)
				.hide()
				.fadeIn(900);
			}
			
			preview.src = vars.randomHP+noCache;
			
			$(window)
			.resize(function(){ 
				vars.jqphotos_size = {
					w : vars.jqphotos.innerWidth(),
					h : vars.jqphotos.innerHeight()
				};
				
				if( $('body').hasClass('with-secondtier-nav') ){
					vars.jqphotos_size = {
						w : vars.jqphotos_size.w-370,
						h : vars.jqphotos_size.h-370
					};
				}
				
				var dem = get_size( vars.jqphotos_photo.data('w'), vars.jqphotos_photo.data('h'), vars.jqphotos_size.w, vars.jqphotos_size.h );
				
				vars.jqphotos_photo
				.width( dem.w )
				.height( dem.h )
			});
			
			if( $.browser.msie && $.browser.version < 8 ){
				$('#quotes')
				.html( homeflash );
			}
		}
	},
	'quotes-on-page' : {
		init : function(){
			echo('core -> quotes-on-page -> init','info');
		    $("#quotes")
		    .cycle({
			 fx:     'fade',
			 speed:  1000,
			 timeout:4000
		    });	
		}
	},
	'animated-menu' : {
		init : function(){
			echo('core -> animated-men -> init','info');
			var jqdummy_nav = $('.wrap .colOne .dummy-nav').show();
			var jqprimary_nav = $('.wrap .colOne .primary-nav')
							.css('left',-155)
							.children(':first')
								.css('left',-155)
							.end();
			var jqcolOne = $('.colOne')
						.mouseenter(function(){
							jqdummy_nav.animate({'left':-155}, 300, 'linear',
							function(){
								jqprimary_nav
								.children(':first')
									.animate({'left':0}, 300, 'linear');
							});
							jqprimary_nav.animate({'left':0}, 300, 'linear');
						})
						.mouseleave(function(){
							$(this)
							.animate({opacity: 1.0},3000,function(){
								jqprimary_nav
								.children(':first')
									.animate({'left':-155}, 300, 'linear',
									function(){
										jqprimary_nav.animate({'left':-155}, 300, 'linear');
										jqdummy_nav.animate({'left':0}, 300, 'linear');
									});
							});
							
						});
		}
	},
	courtyard	: {
		interior: function(){
			echo('core -> courtyard -> interior','info');
			if( $.browser.msie && $.browser.version < 8 ){
				$('#quotes')
				.html( drawingflash );
			}
		}
	},
	rooms : {
		init	: function(){
			echo('core -> room -> init','info');
		},
		interior : function(){
			echo('core -> room -> interior','info');
			// to help fix the rapping
			//$('#main').css('padding-bottom',19);
		}
	}
};

//qualify an HREF to form a complete URI
function qualifyHREF(href)
{
	//get the current document location object
	var loc = document.location;

	//build a base URI from the protocol plus host (which includes port if applicable)
	var uri = loc.protocol + '//' + loc.host;

	//if the input path is relative-from-here
	//just delete the ./ token to make it relative
	if(/^(\.\/)([^\/]?)/.test(href))
	{
		href = href.replace(/^(\.\/)([^\/]?)/, '$2');
	}

	//if the input href is already qualified, copy it unchanged
	if(/^([a-z]+)\:\/\//.test(href))
	{
		uri = href;
	}

	//or if the input href begins with a leading slash, then it's base relative
	//so just add the input href to the base URI
	else if(href.substr(0, 1) == '/')
	{
		uri += href;
	}

	//or if it's an up-reference we need to compute the path
	else if(/^((\.\.\/)+)([^\/].*$)/.test(href))
	{
		//get the last part of the path, minus up-references
		var lastpath = href.match(/^((\.\.\/)+)([^\/].*$)/);
		lastpath = lastpath[lastpath.length - 1];

		//count the number of up-references
		var references = href.split('../').length - 1;

		//get the path parts and delete the last one (this page or directory)
		var parts = loc.pathname.split('/');
		parts = parts.splice(0, parts.length - 1);

		//for each of the up-references, delete the last part of the path
		for(var i=0; i<references; i++)
		{
			parts = parts.splice(0, parts.length - 1);
		}

		//now rebuild the path
		var path = '';
		for(i=0; i<parts.length; i++)
		{
			if(parts[i] != '')
			{
				path += '/' + parts[i];
			}
		}
		path += '/';

		//and add the last part of the path
		path += lastpath;

		//then add the path and input href to the base URI
		uri += path;
	}

	//otherwise it's a relative path,
	else
	{
		//calculate the path to this directory
		path = '';
		parts = loc.pathname.split('/');
		parts = parts.splice(0, parts.length - 1);
		for(var i=0; i<parts.length; i++)
		{
			if(parts[i] != '')
			{
				path += '/' + parts[i];
			}
		}
		path += '/';

		//then add the path and input href to the base URI
		uri += path + href;
	}

	//return the final uri
	return uri;
}

$(document).ready(UTIL.loadEvents);
