$(function() {
	$(document).pngFix({
	    blankgif:'/images/blank.gif'
	});
	// for debugging IE...
	if ( location.href.indexOf('debugger') != -1 ) {
	    $('<div id="debugger"></div>').appendTo('body')
	    $('<iframe/>').attr('src', 'javascript:false').attr('id', 'debugger-shim').appendTo('body')
	    $('<form id="console-form"><textarea name="text" id="console-input"></textarea><input type="submit" value="Run"/></form>').appendTo('#debugger');
	    $('<ol/>').appendTo('#debugger');
	    $('#console-form').submit(function(e) {
		e.preventDefault()
		eval( $('#console-input').val() );
	    });
	}
	window.log = function( msg ) {
	    if ( window.console && console.log ) {
		console.log( msg )
	    }
	    if ( $('#debugger').length ) {
		$('#debugger ol').append( $('<li/>').text( msg ) );
	    }
	}
	
	//anything other than just a hash sign, let's scrollto
	if ( location.hash.length>1 ) {
	    $.scrollTo('#content');
	}
	//booking console
	$('.toggle-promo').click(function(e){
		e.preventDefault();
		$('#promo-console').toggle(0,function(){
			if($(this).is(':visible')) {
				$('#group-code').focus();
			}
			else {
				$('.submit').focus();
			}
		});
		if (BROWSER=='msie6') $('#basic-console select').toggle();
		if ($('#group-code').val() || $('#promo-code').val() || $('#iata-number').val()) {
			$('#complete-promo').show();
		}
		else {
			$('#complete-promo').hide();
		}
	});
	
	$('#map-experiences a, #map-regions a').click(function(e){
		e.preventDefault();
		$('.map-destinations li a').css({color:'#ffffff'}).parents('.'+$(this).attr('rel')).children().animate({color:'#5f5244'},100).animate({color:'#79d6ff'}, 1000);
	});
	
	$('.filter').click(function(e){e.preventDefault();$(this).siblings().toggle();})
	    if ( $.fn.cycle ) {
		$('div.rotation-wrapper').cycle({
				fx:'scrollLeft',
				pause:1,
				timeout:0,
				next:'.rotation-next',		// selector for element to use as click trigger for next slide 
				slideExpr:'.rotation-item',
				cleartype:true,
				cleartypeNoBg:true,
				height:'180px',
				fastOnEvent:250	// force fast transitions when triggered manually (via pager or prev/next); value == time in ms 
		});
	    }
	var state='', city = '', type='', xml='', experience='';
	$('.state-map').each(function(){
		var arrPath = $(this).attr('id').split('_');
		if (arrPath[0]=='experiences'){
			state=arrPath[2];
			if(arrPath.length > 4) {
				city=arrPath[3];
			}
			xml='/xml/experience_map.xml';
			type='experiences';
			experience=arrPath[1];
		} else {
			state=arrPath[1];
			if(arrPath.length > 3) {
				city=arrPath[2];
			}
			xml='/xml/property_map.xml';
		}
	});
	$('.state-map').flash(
		{src:"/flash/state-map.swf",
		 width:191,
		 height:204,
		 wmode:"transparent",
		 quality:"high"},
		 {version:"8"},
			function(htmlOptions) { //Use this to specify a query string, take out if not needed.
				htmlOptions.flashvars.stateID = state;
				htmlOptions.flashvars.cityID = city;
				htmlOptions.flashvars.xmlPath=xml;
				htmlOptions.flashvars.mapType = type;
				htmlOptions.flashvars.experience = experience;
				htmlOptions.flashvars.browser = BROWSER;  //Used for SSP Postcard feature, comment out if not needed.
				$(this).html($.fn.flash.transform(htmlOptions));
		});
	var type = '';
	var experience = '';
	var xml = '';
	$('.experience-map').each(function(){
	    if ( $.hasFlash() ) {
		$(this).css('display', 'inline');
	    }
		var arrPath = $(this).attr('id').split('_');
		//alert(arrPath.length);
		if (arrPath[0]=='experiences'){
			type=arrPath[0];
			experience=arrPath[1];
			xml='/xml/experience_map.xml';
		} else {
			type='states';
			xml='/xml/property_map.xml';
		}
	});
	$('.experience-map').flash(
		{src:"/flash/destination-map.swf",
		 width:412,
		 height:312,
		 wmode:"transparent",
		 quality:"high"},
		 {version:"8"},
			function(htmlOptions) { //Use this to specify a query string, take out if not needed.
				htmlOptions.flashvars.mapType = type;
				htmlOptions.flashvars.experienceType = experience;
				htmlOptions.flashvars.xmlPath=xml;
				htmlOptions.flashvars.browser = BROWSER;  //Used for SSP Postcard feature, comment out if not needed.
				$(this).html($.fn.flash.transform(htmlOptions));
		});
    var pageType = 'destinations';
    var displayCount = 3;
    var xmlPath = '/masthead-parser.php';
    var tags = '';
	var useStatic = false;
    $('.masthead').each(function(){
		//see if a masthead has been added via CMT
		$(this).children('img').css('visibility','visible');
		var altImg = $(this).children('img').attr('src')||'temp-masthead';
		if (altImg.indexOf('temp-masthead') == -1) {
			useStatic=true;
		}
		
        var startIndex = 1;
        var arrPath = $(this).attr('id').split('_');
        if(arrPath[0]!=''){
            pageType = arrPath[0];
            
            if(pageType == 'property'){
                xmlPath = '/resorts/'+arrPath[1]+'/mastheads.xml'; 
                startIndex = 2;
            }else{
                xmlPath = '/masthead-parser.php';
            }
            if(window.MASTHEAD_IMG){
                displayCount = MASTHEAD_IMG;
            }
            for (var i=startIndex;i<arrPath.length;i=i+1){ 
                if(arrPath[i]!='masthead'){
                    if(i!=(arrPath.length-1) && i!=startIndex){
                        tags = tags + "_";
                    }
                    tags = tags + arrPath[i];
                }
            }
        }
        
    });
	if (!useStatic) {
		$('.masthead').flash(
			{src:"/flash/interior-masthead.swf",
			 width:956,
			 height:300,
			 wmode:"transparent",
			 quality:"high"},
			 {version:"8"},
				function(htmlOptions) { //Use this to specify a query string, take out if not needed.
					htmlOptions.flashvars.pageType = pageType;
					htmlOptions.flashvars.displayCount = displayCount;
					htmlOptions.flashvars.xmlPath=xmlPath;
					htmlOptions.flashvars.tags = tags;
					$(this).html($.fn.flash.transform(htmlOptions));
			});
	}
    $('.home .masthead').flash(
        {src:"/flash/home-masthead.swf",
         width:962,
         height:447,
         wmode:"transparent",
         quality:"high"},
         {version:"8"},
            function(htmlOptions) { //Use this to specify a query string, take out if not needed.
                htmlOptions.flashvars.experienceXmlPath = "/xml/experience_map.xml";
                htmlOptions.flashvars.mapPath = "/flash/assets/destination-map.swf";
                htmlOptions.flashvars.xmlPath="/xml/home_mastheads.xml";
                //htmlOptions.flashvars.tags = tags;
                $(this).html($.fn.flash.transform(htmlOptions));
        }).addClass('masthead_flash_home');
	$('#masthead-home-property').hide()
    $('.home #push-rotation-wrapper').flash(
        {src:"/flash/special-offers.swf",
         width:644,
         height:133,
         wmode:"transparent",
         quality:"high"},
         {version:"8"},
            function(htmlOptions) { //Use this to specify a query string, take out if not needed.
                htmlOptions.flashvars.xmlPath="/xml/home-offers-rotation.xml";
                $(this).html($.fn.flash.transform(htmlOptions));
        });
	$('#industry-experts').each(function() {
	    $('.expert-copy').hide();
	    $('.expert').each(function(i,o) {
		var anchor = $('<a/>').attr('id','bio-'+i).addClass('modal-trigger').attr('href', '#').text('Read More')
			.appendTo( o )
		$('.expert-title span', o).click(function() {
		    $(this).closest('.expert').find('.modal-trigger').trigger('click');
		});
	    });
	});
	function contains( string, substring ) {
	    return string.indexOf(substring) != -1;
	}
	//Modal Setup - any links with class="modal-trigger" and id="whatever" will display the contents of the div within #modal-wrapper with id="modal-whatever"
	var openFn = function( hash ){
	    var id = hash.t.id,
		ref = $('#'+id);
		if ( contains( id, 'video') ) {
			hash.w.show().children('#modal-video-all').show();
		}
		else if ( contains( id, 'bio' ) ) {
			var expertId = id + '-modal';
			if ( !$('#'+expertId).length ) {
			    var duplicateTitle = $(ref).siblings('.expert-title').clone(),
				container = $('<div/>')
				    .attr( 'id', expertId )
				    .prepend( $(duplicateTitle) )
				    .addClass('expert-content')
				    .append( $(ref).siblings('.expert-copy') )
				    .appendTo( '#modal-expert' )
				    .find('.expert-copy').show()
			}
			$('#'+expertId).show().siblings('.expert-content').hide()
			hash.w.show().children('#modal-expert').show();
		}
		else {
			hash.w.show().children('#modal-'+hash.t.id).show();
		}
		if ($(hash.t).hasClass('no-overlay')) hash.o.css({backgroundColor:'transparent'});
		var leftPos = ($(window).width()-$('#modal-wrapper').width())/2;
		var topPos = Math.max($(window).scrollTop(),parseInt($('#modal-wrapper').css('top')));
		$('#modal-wrapper').css({left:leftPos,top:topPos});
	};
	var hideFn=function(hash){
		hash.w.hide().css({left:0,top:0}).children('.modal-content').hide();
		hash.o.remove().css({backgroundColor:'#000'});
		$('.video-dhr').remove();
	};
	$('#modal-wrapper').each(function(){ $(this).jqm({trigger:'.modal-trigger', closeClass:'modal-close', overlayClass:'modal-overlay', onShow: openFn, onHide: hideFn});});
	$('#video-list ul li a').live('click', function(e) {
	    log('clicked on a video link')
	    e.preventDefault();
	    var link = $(this).attr('href');
		e.preventDefault();
		var iframe = $('#video-wrapper iframe'), iframeExists = iframe.length;
		if ( iframeExists ) {
		    log('iframe exists, changing the src... to ' + link)
		    $(iframe).attr('src', link);
		    $('.video-dhr')
			.attr('width', '410')
			.attr('height', '320')
			.removeClass('video-dhr');
		    log('toggled the width/height, removed video-dhr class')
		} else {
		    log('no iframe exists, replacing the image with one..')
		    $('#video-wrapper img').replaceWith('<iframe id="modal-iframe" frameborder="0" width="410" height="320" style="display:block;margin:0 auto;" />');
		    log('replaced img with an iframe')
		    $('#modal-iframe').attr('src', link);
		    log('changed the iframe src')
		    $('.video-dhr').removeClass('video-dhr');
		}
	});
	$('#hotel-video').change(function() {
	    var value = $(this).val(), name = $(':selected', this).text();
		//$("#video-wrapper iframe").attr('src','');
		$("#video-wrapper iframe").remove();
		log('iframe removed')
		$("#video-wrapper").html('<img src="/images/layout/modal-intro.jpg" alt="" border="0" />');
		log('.html invoked on #video-wrapper, showing default image and attempting to do ajax...')
	    if ( value ) {
			$.ajax({
				type:'GET',
				url:'/direct/video-request.php',
				data: 'property=' + value,
				success:function( data ) {
				    log('callback from ajax')
					$('#video-list-content').empty().append( data );
					log('within ajax, emptied list-content, appended with data.')
					if ( value == 'dhr-video' ) {
					    $("#video-list-content").html('<ul class="clear-float"><li><a href="http://www.destinationhotels.com/direct/video-dhr.php">Destination Hotels &amp; Resorts</a></li></ul>');
					}
				}
			});
			$('#property-name-lightbox').text( '- ' + name );
	    }
	});
	$('.inset-photos').each(function() {
	    if ( $.hasFlash() ) {
		$(this).css('display', 'inline');
	    }
	    var id = $(this).attr('id'), arr = id.split('_');
	    if ( arr.length ) {
		$(this).flash(
			{src:"/flash/insets.swf",
			 width:285,
			 height:226,
			 wmode:"transparent",
			 quality:"high"},
			 {version:"8"},
				function(htmlOptions) { //Use this to specify a query string, take out if not needed.
					htmlOptions.flashvars.xmlPath='/xml/hotels-resorts/' + arr[0] + '.xml';
					$(this).html($.fn.flash.transform(htmlOptions));
			});
	    }
	});
	$('.help-link').click(function(e){e.preventDefault();$(this).parent().parent().find('.form-help').toggle();});
	// oh well.
	$('#awards-table tr:last td, #articles tr:last td, body.industry-experts tr:last td').css('border', '0');
	
	// Amex Promo form js
	
	$("#amex-promo").each(function(){
		var form = $(this);
		$("select#hotel",form).change(function(){
			form.submit();
		});
	});
	$('#articles img').each(function() {
	    var href = $(this).closest('a').attr('href'),
		nextCell = $(this).closest('td').next()
		    .append( $('<a/>').addClass('read-more').attr('href', href).text('Read the article') );
	});
	var externalLinks = [
	    /\.pdf/,
	    /\.doc/,
	    /^http/
	];
	
	// sup:contains('®') doesn't want to work?
	$("sup").each(function(){temp=$(this).text();if (escape(temp)=="%AE") { $(this).addClass('fixR');}});
	$('a').each(function(i,o) {
	    var href = $(this).attr('href');
	    if ( href ||  !($(this).attr('target').length) ) {
		$(externalLinks).each(function() {
		    if ( this.test(href) ) {
			$(o).attr('target', '_blank');
		    }
		});
	    }
	});
	
	$('#specials-signup').flash(
        {src:"/flash/email-form.swf",
         width:566,
         height:101,
         wmode:"transparent",
         quality:"high"},
         {version:"9"});
	
	/* adds "odd" class to odd rows in tables with class "styled-table" */
	$("table.styled-table tr:nth-child(odd)").addClass("odd");
	
	/*
    $('body.industry-experts table tr').each(function() {
	var first = $('p:first', this), 
	    secondCell = $('td:last', this),
	    rest = $(first).nextAll('p')
		.hide(),
	text = {
	    hide:'Hide Information',
	    show:'Read more about this expert'
	}
	anchor = $('<a/>')
	    .addClass('read-more-expert')
	    .attr('href', '#')
	    .text( text['show'] )
	    .toggle(function() {   
		$(rest).slideDown('fast')
		$(this).text( text['hide'] )
	    }, function() {
		$(rest).slideUp('fast')
		$(this).text( text['show'] )
	    })
	if ( rest.length ) {
	    $(secondCell).append( anchor )
	}
    });
    */
	
	$(".property-listing-points").each(function(){
		var x = $(this);
		$("ul",x).hide();
		$(".property-listing-click",x).toggle(function(){
			$("ul",x).slideDown();
			$(this).html('Hide Details');
		}, function() {
			$("ul",x).slideUp();
			$(this).html('Show Details');
		});
	});
    $('form#form-news-archive select').change(function() {
	$(this).closest('form').submit();
    });
    $('form#form-news-archive .submit').hide();
    if ( location.href == 'http://www.destinationhotels.com/careers' || location.href == 'http://www.destinationhotels.com/careers/' ) {
	$('#utility-careers-careers').addClass('current');
    }
    $('body.home input#email_address').each(function() {
	var defaultText = 'Enter your email address here';
	this.value = defaultText; 
	$(this).click(function(){
	    if ( this.value == defaultText ) {
		this.value = ''
	    }
	});
	$(this).blur(function() {
	    if ( this.value.length === 0 ) this.value = defaultText
	});
    });
    $('#filters-wrapper').each(function() {
	$(this).find('.current').parent().show()
    });
	
});
