// custom jquery selectors
$('img').load(function()
{ 
  $(this).data('loaded',true);
});

$.extend($.expr[':'],
{
  loaded:function(a)
  {
    return $(a).data('loaded');
  }
});

function removeImgToolbar()
{
  $('img').each(function(){
    $(this).attr('galleryimg','no');
  });
};

function randomHP()
{
  
  var totalHP = 3;
  var rndNum = Math.floor(Math.random() * totalHP)+1;
  var path = '/_assets/images/home/greenwich_hotel-homepage-0'+rndNum+'.jpg';
  return path;
}

function resizeImage(dim, h, w)
{
	echo('','trace');

	echo('resizeImage','info');
	echo('dim='+dim,'info');
	echo('h='+h,'info');
	echo('w='+w,'info');

  var wW = photo.width();
  var wH = photo.height();
  var dH = $(document).height();
  
/*
	echo('wW='+wW,'info');
	echo('wH='+wH,'info');
	echo('dH='+dH,'info');
  */
  
  switch(dim)
  {
    case 'height':
      var pD = (w/h)*wH;
      pimg.css('height', wH);
      $('.fullscreen #photos img').css({'width':wW});
      break;
      
    case 'width':
    
      var pD = (h/w)*wW
        pimg.css({'height':pD, 'width': wW});
        $('.fullscreen #photos img').css({'width':wW});
        
        switch (true)
        {
          case (pD < dH):
            pD = (w/h)*dH;
            pimg.css({'height': dH, 'width':pD});
            
          break;
        }
      break;
  }
  if ($('#interior.rooms .detail').length)
  {
    p = $('#nav-info li').eq(1).position();
     echo ('ptop='+p.top,'info');
    switch(true)
     {
       case (dH -75 < p.top):
         $('body').addClass('float');
         $('#nav-rooms').addClass('float');
         $('#siteinfo').addClass('float');
         $(jqbgTier1).height(dH+75);
         $(jqbgTier2).height(dH+75);
         $(jqbgTier3).height(dH+75);
         $(photo).height(dH+75);
         $(pimg).height(dH+75);
         $('#content').height(dH+75);
       break;

       case (dH -75 > p.top):
          $('body').removeClass('float');
         $('#nav-rooms').removeClass('float');
         $('#siteinfo').removeClass('float');
          $(jqbgTier1).css('height','100%');
          $(jqbgTier2).css('height','100%');
          $(jqbgTier3).css('height','100%');
          $(photo).css('height','100%');
          $(pimg).css('height','100%');
          $('#content').css('height','100%');
       break;
     }}
  return true;
};
var gdimHeight = gdimWidth = null;
function findDim(dimHeight, dimWidth)
{
  if(!dimHeight)
  {
    dimHeight = pimg.width();
    dimWidth = pimg.height();
  }

	gdimHeight = dimHeight;
	gdimWidth = dimWidth;
  $(window).trigger('resize');
  return true;
}

// window resize was getting "binded" multiple times causeing issues
$(function(){
	$(window).bind('resize.custom',function(){
		switch(true)
		{
			case (gdimHeight > gdimWidth): 
				return (resizeImage('height', gdimHeight, gdimWidth));
				break;
			case (gdimHeight < gdimWidth): 
				return (resizeImage('width', gdimHeight, gdimWidth));
				break;
		}
	});
});


function presentImage(src)
{

	var parent = pimg.parent();
	// pimg.remove();

	var image = pimg.attr('src','').removeAttr('style');//$('<img />')
  
	$(image)
	.css({position:'absolute',left:'-999em',top:'-999em'})
	.load(function(){
		pimg = $(this).unbind('load');;
		
		$(parent).append($(this));
		var pH = $(this).height();    
		var pW = $(this).width();
		
		pW = this.width;
		pH = this.height;
		
		pimg.hide().css({position:'',left:'',top:''})
		
		if(findDim(pH,pW))
		{
		 image.animate({opacity:'show'},{duration:900,easing:'linear'});
		}
	}).attr('src', src);
}

$(document).ready(function() {
  photo = $('#photos');
  pimg = $('#photos img');
  jqbgTier2 = $('#bg-tier2');
  jqbgTier1 = $('#bg-tier1');
  jqbgTier3 = $('#bg-tier3');
  jqnTier2 = $('#nav-tier2');
  jqnTier1 = $('#nav-tier1');
  jqMain = $('#main');
  
  
  $('#nav-menu').hide();
  if($('#index').length)
  {
    presentImage(randomHP());
    $("#quotes")
    .cycle({
      fx:     'fade',
      speed:  1000,
      timeout:4000
    });

    
    
    initMenu();
    runMenu();
  }
  
  if ($('#interior:not(.presslist)').length)
  {
    presentImage(pimg.attr('src'));
  }
  
  if ($('#interior.rooms .landing').length)
  {
    roomsMenu();
   
  }
  
  if ($('#interior.rooms .detail').length)
  {
    galleryNav();
    
    $('#nav-tier1 .rooms a').click(function(e){
      e.preventDefault();
      
    })
  }
  if ($('#interior.courtyard').length)
  {
    
    
    galleryNav();
  }
  if ($('#interior.spa.start').length)
  {
   
    spaMenu();
      galleryNav();
  }
  if ($('#interior.spa.home').length)
  {
  }
  if ($('#interior.spa').length)
  {
    
    galleryNav();
    $('#main a').click(function(e){
      e.preventDefault();
      $('<div class="wrap" style="display: none"></div>').load('/spa/detail.php #detail').insertAfter("#main").show(300, function(){
        $('.close a').click(function(e){e.preventDefault(); $('#content .wrap .wrap').remove();});
      });
    })
    
  }
  if ($('#interior.pool').length)
  {
    
    galleryNav();
  }
  if ($('#interior.map').length)
  {
    loadMap();
  }
  if ($('#interior.gal').length)
  {
    galleryNav();
    initMenu();
    runMenu();
  }
  if ($('#interior.presslist').length)
  {
    $('#interior.presslist .press:nth-child(4)').addClass('last');
    runPress();
    pressNav();
  }
  if ($('#interior.restaurant').length)
  {
    
  }
   
   
  pageNav();

  removeImgToolbar();

  $("a[rel=external]").live('click', function(e){
    e.preventDefault();
    window.open(this.href);
  })
  
});


galleryPages = function( image_url, cls_arr ){
	var cur = 0;
	var lstcls = null;
	$('#nav-gallery .next a').unbind('click').click(function(e){
		echo('hit');
		e.preventDefault();

		if (cur == (image_url.length-1)) {
			cur = -1;
		}
		
		checkHide(++cur == 0);
		
		checkClassed(cls_arr, cur);
		
	    pimg.animate({opacity:'hide'},{duration:300,easing:'linear',complete:function(){
	      _presentImage( image_url[cur] );
	    }});
				
		return false;
	});
	$('#nav-gallery .prev a').unbind('click').click(function(e){
		e.preventDefault();

		if (cur == 0) {
			cur = image_url.length;
		}
		
	    pimg.animate({opacity:'hide'},{duration:300,easing:'linear',complete:function(){
			_presentImage( image_url[--cur] );
			
			checkHide(cur == 0);
			
			
			checkClassed(cls_arr, cur);
	    }});
				
		return false;
	});
	
	function checkClassed(cls_arr, cur){
		if( typeof cls_arr != 'undefined' && typeof cls_arr[cur] != 'undefined' ){
			$('#nav-gallery').removeClass(lstcls);
			lstcls = cls_arr[cur];
			$('#nav-gallery').addClass(lstcls);
		}
		else{
			$('#nav-gallery').removeClass(lstcls);
		}
	}
	
	function checkHide(hide){
		if( !hide )
		 	$("#quotes").css({'position':'absolute','left':'-999em','top':'-999em'});
		else
		 	setTimeout(function(){$("#quotes").css({'position':'',left:'',top:''});}, 1000)
	}
	
	$(window).bind('load.preload',function(){
		$(window).unbind('load.preload');

	    for (var i = 0; i < image_url.length; i++) {
			var img = Array();
			img[ i ] = new Image();
			img[ i ].src = image_url[i];
		}
	});
}

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){}
}

/* bens code */
var jqphotos = jqimage = null;
var curImgHeight = curImgWidth = null;
/* @start _presentImage */
function _presentImage(src){
	// check to see if jqphoto is set to the div with the id photos
	if( !jqphotos ){
		jqphotos = $('#photos');
	}
	
	if( !jqimage ){
		jqimage = $('#photos img:eq(0)');
	}

	// remove the src value, the style attribute and set the position off
	//	screen to help with ie6 crap
	jqimage
		.attr('src','')
		.removeAttr('style')
		.css({position:'absolute',left:'-999em',top:'-999em'});
	
	// a variable to help against IE not always setting the .complete
	var running = false;
	
	// this will run when the image is onloaded on completely loaded (ie. cached)
	function _run(){
		this.onload = null;
		running = true;
		curImgHeight  = this.height;
		curImgWidth  = this.width;
		
		jqimage
			.hide()
			.css({position:'',left:'',top:''})
			.attr('src', src);
		
		if( findDim( curImgHeight, curImgWidth ) )		{
			jqimage.animate({opacity:'show'},{duration:900,easing:'linear'});
		}
	}
	
	// create a new image because saf and ie won't respect any other method
	var image = new Image();
	image.onload = _run;
	image.src = src;
	
	// check to see if the image is completely loaded and if the onload is 
	//		already running.
	if( image.complete && !running ){
		image.onload = null;
		_run.call( image );
	}
}
/* @end _presentImage */

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');
  } 
}; 

var core = {
	common : {
		init     : function(){
			if( $.browser.msie ){
				$('#nav-rooms li.prev a, #nav-rooms li.next a')
				.css({'letter-spacing':'0px','font-family':'Arial, Helvetica, sans-serif'});
			}
		},
		finalize : function(){
		}
	},
	home : {
		'index' : function(){
			if( $.browser.msie && $.browser.version < 8 ){
				$('#quotes')
				.html( homeflash );
			}
		}
	},
	courtyard	: {
		interior: function(){
			if( $.browser.msie && $.browser.version < 8 ){
				$('#quotes')
				.html( drawingflash );
			}
		}
	},
	rooms : {
		init	: function(){},
		interior : function(){
			// to help fix the rapping
			$('#main').css('padding-bottom',19);
		}
	}
}
 
// kick it all off here 
$(document).ready(UTIL.loadEvents);

$(document).ready(function(){
	// remove the alt text for the main photos
	$('[alt]').removeAttr('alt');		   
});

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>';


