//******************************************
// HOME PAGE SCRIPTS
//******************************************
    //******************************************
    // AddThis Listener Assignment
    //******************************************
    /*
    var add_button = null;
    addthis.addEventListener('addthis.menu.share', shareEventHandler);
    $('.addthis_button').mouseover(function() {
      add_button = $(this);
    });
    function shareEventHandler(evt) {
      if (evt.type == 'addthis.menu.share') {
        alert(add_button.attr('addthis:url') + '/share/' + evt.data.service);
        pageTracker._trackPageview(add_button.attr('addthis:url') + '/share/' + evt.data.service);
      }
    }
    */

/* HTML ACCORDION SCRIPTS
============================== */

// Prep window Heights & Pages Positions 
//======================================
$(function(){
	$('#home-accordion .window').each(function(index,win){
		$(this).find('.page').each(function(i){
			$(this).css('left',(338*i));
			if(parseFloat($(win).css('minHeight')) < $(this).outerHeight()){
				$(win).css('minHeight',$(this).outerHeight());
			}
		});
	});
	$(".textsize a").click(function(e) {
		$('#home-accordion .window').each(function(index,win){
			$(this).find('.page').each(function(i){
				if(parseFloat($(win).css('minHeight')) < $(this).outerHeight()){
					$(win).css('minHeight',$(this).outerHeight());
				}
			});
		});
	});
});

// Prep Tabs
//============================
$(function(){
	$('#home-accordion .title').each(function(i){
		if(i==0){
			$(this).addClass('active');
		}
	});
	$('#home-accordion .content').each(function(i){
		if(i==0){
			$(this).addClass('first').addClass('activeContent');
		} else {
			$(this).css('display','none');
		}
	});
});
// Open/Close Tabs
//============================
$(function(){
	$('#home-accordion .title').each(function(index){
		$(this).click(function(){
			// Stop any playing YouTube videos
			$('#home-accordion .window:not(#podcasts .window)').prev('.video').each(function(videoIndex){
				if($(this).parent('.activeContent').length>0 && $(this).find('.ytContainer').length < 1){
					eval('ytplayer'+videoIndex).pauseVideo();
					if(jQuery.support.opacity){ // Targeting <=IE8
						$(this).css('visibility','hidden');
					}
				}
			});
			// Stop Podcast from playing
			$('#home-accordion #podcasts .window').prev('.audio').each(function(index){
				if($(this).find('.playing').length>0){
					podcastAudio.pause();
				}
			});
			// Open/Close Tabs
			$('#home-accordion .content').each(function(contentIndex){
				if(contentIndex!=index){
					$(this).slideUp(500).removeClass('activeContent');/* Close other tabs*/
				} else{
					//$(this).slideDown(500).addClass('activeContent');/* Open new tab*/
					$(this).slideDown(500, function(){
						$(this).find('.video').css('visibility','visible');
					}).addClass('activeContent');
					
				}
			});
			/* Change title arrow direction */
			$('#home-accordion .title').each(function(titleIndex){
				if(titleIndex!=index){
					$(this).removeClass('active');
				} else {
					$(this).addClass('active');
				}
			});
		});
	});
});
// Add Prev/Next Links to Thumbs
//==============================
$(function(){
	$('#home-accordion .window').each(function(){
		if($(this).find('.page').length > 1){
			// Prep Pagination Container & Insert in Page
			$('<div class="pagination"> \
				<a href="#" class="prev">&lt;</a> \
				<div class="pages"></div> \
				<a href="#" class="next active">&gt;</a> \
			</div>').insertAfter(this);
			$(this).find('.page').each(function(index){
				$('<a href="#"><span>'+(index+1)+'</span></a>').appendTo($(this).parent().parent().find('.pagination .pages'));
				if(index==0){ $(this).parent().parent().find('.pagination .pages a').addClass('active'); }
			});
		}
	});
});
// Handle Prev/Next & Page Links
//==============================
var pageSlideSpeed = 800;
$(function(){
	$('#home-accordion .content .window').each(function(winIndex,win){
		// Setup page tracking variables
		eval('var accordionCurPage'+winIndex+' = 0');
		eval('var accordionPageLength'+winIndex+' = '+$(this).find('.page').length);
		
		
		$(this).next().find('a').each(function(aIndex,e){
			$(this).click(function(){
				var curPage = eval('accordionCurPage'+winIndex);
				var nextPage;
				var totalPages = eval('accordionPageLength'+winIndex);
				
				// If Previous link
				if(aIndex==0){
					if(curPage==0){ return false; }
					nextPage = curPage-1;
					$(this).parent().prev().find('.page').each(function(pageIndex){
						$(this).stop().animate({
							left: parseFloat($(this).css('left'))+338
						},pageSlideSpeed, function(){
							eval('accordionCurPage'+winIndex+' = '+nextPage);
							if(pageIndex==0){
								setAccordionButtonStates(winIndex, nextPage);
							}
						});
					});
				}
				// If a Page link
				else if(aIndex>0 && aIndex<$(this).parents('.pagination').find('a').length-1){
					if(curPage==aIndex-1){ return false; }
					nextPage = aIndex-1;
					$(this).parent().parent().prev().find('.page').each(function(pageIndex){
						$(this).stop().animate({
							left: parseFloat($(this).css('left'))+((curPage-nextPage)*338)
						},pageSlideSpeed, function(){
							eval('accordionCurPage'+winIndex+' = '+nextPage);
							if(pageIndex==0){
								setAccordionButtonStates(winIndex, nextPage);
							}
						});
					});
				}
				// If Next link
				else {
					if(curPage==totalPages-1){ return false; }
					nextPage = curPage+1;
					$(this).parent().prev().find('.page').each(function(pageIndex){
						$(this).stop().animate({
							left: parseFloat($(this).css('left'))-338
						},pageSlideSpeed, function(){
							eval('accordionCurPage'+winIndex+' = '+nextPage);
							if(pageIndex==0){
								setAccordionButtonStates(winIndex, nextPage);
							}
						});
					});
				}
				
				return false;
			});
		});
	});
});
function setAccordionButtonStates(winIndex,nextPage){
	var curPage = nextPage;
	$('#home-accordion .content .window').each(function(i){
		if(i == winIndex){
			if(curPage==0){
				$(this).next().find('.prev').removeClass('active');
				$(this).next().find('.next').removeClass('active').addClass('active');
			} else if(curPage>0 && curPage<$(this).find('.page').length-1){
				$(this).next().find('.prev').removeClass('active').addClass('active');
				$(this).next().find('.next').removeClass('active').addClass('active');
			} else if(curPage == $(this).find('.page').length-1) {
				$(this).next().find('.prev').removeClass('active').addClass('active');
				$(this).next().find('.next').removeClass('active');
			}
			$(this).next().find('.pages a').each(function(i){
				if(i!=curPage){
					$(this).removeClass('active');
				} else {
					$(this).addClass('active');
				}
			});
		}
	});
}

// Prep YouTube Videos
//======================================
$(function(){
	$('#home-accordion .window:not(#podcasts .window)').each(function(index){
		// Grab first YouTube video
		var videoURL  = $(this).find('a[href^="http://www.youtube.com"]:first').attr('id').substring(3);
		var videoFull = $(this).find('a[href^="http://www.youtube.com"]:first').attr('rel');
		// Insert Video Div, Embed Obj for non-flash and Full Video Link
		$('	<div class="video" style="visibility:hidden"> \
			<div class="ytContainer" id="yt' + index + '"> \
				<embed id="myytplayer'+index+'" src="http://www.youtube.com/v/'+videoURL+'?rel=0&amp;fs=1&amp;showinfo=0&amp;enablejsapi=1&amp;playerapiid=ytplayer'+index+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="338" height="215"></embed> \
			</div> \
			<p><a href="'+videoFull+'">Watch entire video</a></p></div>').insertBefore(this);
		// Use SWFObject to embed YouTube
		var params = { allowScriptAccess: "always", allowfullscreen: "true", wmode: "opaque" };
    	var atts = { id: "myytplayer"+index };
	    swfobject.embedSWF("http://www.youtube.com/v/" + videoURL + "?rel=0&amp;fs=1&amp;showinfo=0&amp;enablejsapi=1&amp;playerapiid=ytplayer"+index, "yt"+index, "338", "215", "8", null, null, params, atts);

		// Set first video to active
		$(this).find('li:first').addClass('active');
		
		// If tab is open, remove hidden visibility
		if($(this).parents().find('div.content').hasClass('activeContent')){
			$(this).parent().find('div.video').css('visibility','visible')
		}
	});
});
// For YouTube API
function onYouTubePlayerReady(playerId) { 
	var index = playerId.substring(8);
	if(index==0){
		ytplayer0 = document.getElementById("myytplayer0");
	} else if(index==1){
		ytplayer1 = document.getElementById("myytplayer1");
	}
}
// Load YouTube Videos
//==============================
$(function(){
	$('#home-accordion .content .window:not(#podcasts .window)').each(function(winIndex,win){
		$(this).find('.thumbs a[href^="http://www.youtube.com/"]').each(function(){
			$(this).click(function(){
				var youtubeID = $(this).attr('id').substring(3);
				var fullVideo = $(this).attr('rel');
				
				// If browser supports Flash
				if($(this).parents('.activeContent').find('.video .ytContainer').length < 1){
					eval('ytplayer'+winIndex).loadVideoById(youtubeID);
				} else {
					$(this).parents('.activeContent').find('.video .ytContainer embed').remove();
					$(this).parents('.activeContent').find('.video .ytContainer').html('<embed id="myytplayer'+winIndex+'" src="http://www.youtube.com/v/'+youtubeID+'?rel=0&amp;fs=1&amp;showinfo=0&amp;enablejsapi=1&amp;playerapiid=ytplayer'+winIndex+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="338" height="215"></embed>')
				}
				// Update View Entire Video Link
				$(this).parents('.window').prev().find('p a').attr('href',fullVideo);
				// Set Active Class
				$(this).parents('.thumbs').find('li').removeClass('active');
				$(this).parent('li').addClass('active');
				
				// Add Google Analytics Event Tracking
				var linkTitle = $(this).text();
				linkTitle = linkTitle.replace(/^\s+|\s+$/g,"");
				if(location.href.indexOf('192.')==-1 && location.href.indexOf('dev.traveltex')==-1 && location.href.indexOf('beta.traveltex')==-1){ // Only if live site
					//_gaq.push(['_trackEvent', 'HomeAccordion', 'YouTube', linkTitle]);
					pageTracker._trackEvent('HomeAccordion', 'YouTube', linkTitle);
				}
				return false;
			});
			
		});
	});
});
// Prep Podcast  & Thumbs
//======================================
// Init Audio.js
var podcastAudio;
$(function(){
	if($('#home-accordion').length>0){
		var a = audiojs.createAll();
		podcastAudio = a[0];
	}
	$('#home-accordion #podcasts .window').each(function(){
		// Grab first Podcast MP3, Image & Link
		var audioFile = $(this).find('a:first').attr('rel');
		var photo	  = $(this).find('a:first').find('img').attr('src');
		var url		  = $(this).find('a:first').attr('href');
		var city 	  = $(this).find('a:first').text();
		// Insert Audio object, Photo and Link
		$(this).prevAll('.audio').find('.photo').html('<img src="'+photo+'" width="328" height="157" alt="'+city+'" />');
		podcastAudio.load(audioFile);
		$(this).prevAll('.link').html('<a href="'+url+'">Listen to the entire '+ city +' Walking Tour</a>');
		// Set first podcast to active
		$(this).find('li:first').addClass('active');
		
		
		
	});
});
// Handle Podcast Links
//======================================
$(function(){
	$('#home-accordion #podcasts .window').each(function(winIndex,win){
		$(this).find('.thumbs a').each(function(){
			$(this).click(function(){
				// Grab Podcast MP3, Image & Link
				var audioFile = $(this).attr('rel');
				var photo	  = $(this).find('img').attr('src');
				var url		  = $(this).attr('href');
				var city	  = $(this).text();
				// Insert Audio object and Photo
				$(this).parents('.window').prevAll('.audio').find('.photo').html('<img src="'+photo+'" width="328" height="157" alt="'+city+'" />');
				podcastAudio.load(audioFile);
				podcastAudio.play();
				$(this).parents('.window').prevAll('.link').html('<a href="'+url+'">Listen to the entire '+city+' Walking Tour</a>');
				// Set first podcast to active
				$(this).parents('.thumbs').find('li').removeClass('active');
				$(this).parent('li').addClass('active');
				
				// Add Google Analytics Event Tracking
				var linkTitle = $(this).text();
				linkTitle = linkTitle.replace(/^\s+|\s+$/g,"");
				if(location.href.indexOf('192.')==-1 && location.href.indexOf('dev.traveltex')==-1 && location.href.indexOf('beta.traveltex')==-1){ // Only if live site
					//_gaq.push(['_trackEvent', 'HomeAccordion', 'Podcasts', linkTitle]);
					pageTracker._trackEvent('HomeAccordion', 'Podcasts', linkTitle);
				}
				
				return false;
			});
			
		});
	});
});



$(document).ready(function() {

	// Add Homepage Flash Hero
    //========================
    /*$('#homepage_flash_hero_alt').flash(
        {
            src: 'flash/TravelTex_flash_header.swf',
            width: 959,
            height: 386,
            wmode: "opaque",
            id: "homepage_flash_hero"
            //flashvars: { foo: 'bar', baz: 'zoo' }
        },
        { update: false,
            version: '9.0.0'
        }
    );*/


    // Add Accordion Flash
    // (This is now replaced with HTML version above)
	//===============================================
    /*$('#home_accord_flash_alt').flash(
        {
            src: 'flash/accordion.swf',
            width: 338,
            height: 375,
            wmode: "opaque",
            id: "home_accordion"
        },
        { update: false,
            version: '9.0.0'
        }
    );*/

	
	/* ROTATING HOME HERO PHOTO
		& ROTATING HOME FEATURED IMAGE
	===================================*/
	var time = 10000;
	var fadeSpeed = 1000;
	var imgPath = "/images/";
	// Hero Images
	var homepageImgs = new Array(
		"homepage_hero_topchef.jpg",
		"homepage_hero_winter_2011.jpg",
		"homepage_hero_mobile.jpg",
		"homepage_hero_webisodes.jpg");
	var homepageLinks = new Array();
		homepageLinks[0] = ['/topchef','http://www.bravotv.com/top-chef'];
		//homepageLinks[1] = ['/search?q=&t=Event&sd=09/23/2011&ed=12/22/2011'];
		homepageLinks[1] = ['/search?q=Winter'];
		homepageLinks[2] = ['/mobile'];
		homepageLinks[3] = ['/multimedia/texas-videos'];
	var homepageCoords = new Array();
		// [] = single link for entire image
		homepageCoords[0] = ['0,0,959,0,959,131,713,131,713,211,791,211,791,132,959,132,959,336,0,336,0,0','713,131,791,211'];
		homepageCoords[1] = [];
		homepageCoords[2] = [];
		homepageCoords[3] = [];
	// Featured Images (**NOTE: Also must be changed in Default.aspx**)
	//var homepageFeaturedImgs = new Array("homepage_featured_texasVideos.jpg","homepage_featured_texasMusic.jpg","homepage_featured_podcasts.jpg");//,"homepage_featured_txLoneStar.jpg"
	//var homepageFeaturedLinks = new Array("/multimedia/texas-videos","/things-to-do/attractions/music","/multimedia/podcast-walking-tours");//,"http://beourtexaslonestar.com/"
	// Initialize Variables
	var heroTimer; var navTimer; var curImg = 0; var curFeaturedImg = 0; var nextImg; var nextFeaturedImg; var continueRunning = true;
	// Setup Preload Check Vars
	var totalImgs = homepageImgs.length; for(var p=0; p<totalImgs; p++){window['img'+p] = 0;}
	//var totalFeaturedImgs = homepageFeaturedImgs.length;for(var p=0; p<totalFeaturedImgs; p++){window['featuredImg'+p] = 0;}
		
	$(document).ready(function(){
		
		if($('#homepage_hero').length>0){
			// Add Hero Nav
			var heroNav = $('<div id="heroNav"> \
								<a href="#" id="heroNav1" class="heroNav active"></a> \
								<a href="#" id="heroNav2" class="heroNav"></a> \
								<a href="#" id="heroNav3" class="heroNav"></a> \
								<a href="#" id="heroNav4" class="heroNav"></a> \
							</div>');
			heroNav.prependTo($('#overlay_flash_feat'));
			
			// Preload images
			preloadImgs(0);
			//preloadFeaturedImgs(0);
			
			// Trigger animation timer
			heroTimer = setTimeout("$.nextImg()",time);
		}
		$.nextImg = function(){
			clearTimeout(heroTimer);
			
			// === HERO ROTATION =============
			// If user has not clicked heroNav...
			if(continueRunning){
				// Find next image number
				nextImg = curImg<(totalImgs-1) ? curImg+1 : 0;
				// Make sure the next images are preloaded
				if(eval('img'+nextImg) != 1 /*&& eval('featuredImg'+nextFeaturedImg) != 1*/){
					// If image isn't preloaded yet, retry
					heroTimer = setTimeout("$.nextImg();",500); // Timer moved back up here for Featured Rotation removal
					// NOTE: Retry is now moved to "FEATURED ROTATION" area below
						//heroTimer = setTimeout("$.nextImg(); $.nextFeaturedImg()",500);
				} else if(continueRunning) {
					// Setup next image
					var nextHeroImg = $("<div id='nextHeroImg'><img src='"+imgPath+homepageImgs[nextImg]+"' width='959' height='336' border='0' usemap='#hero-map' /></div>");
					$("#heroImg").after(nextHeroImg);
					// Start fading out current image and make the next image the current one; and change hero nav
					// Nav
					if(continueRunning==true){navTimer = setTimeout('$("#heroNav'+(curImg+1)+'").removeClass("active"); $("#heroNav'+(nextImg+1)+'").addClass("active");',fadeSpeed/2);}
					// Image
					$("#heroImg").animate({opacity: 0}, fadeSpeed,
						function(){
							if(continueRunning==true){
								$("#heroImg").remove();
								$("#nextHeroImg").attr("id","heroImg");
								curImg = curImg<(totalImgs-1) ? nextImg : 0;
								// Set Image Map
								if(homepageLinks[curImg].length > 1){ // More than one link
									var maps = '';
									for(var m=0; m<homepageLinks[curImg].length; m++){
										var target = (homepageLinks[curImg][m].toString().indexOf('http')!=-1) ? 'target="_blank"' : '';
										var shape  = (homepageCoords[curImg][m].split(',').length == 4) ? 'rect' : 'poly';
										maps += '<area shape="'+ shape +'" coords="'+ homepageCoords[curImg][m] +'" href="'+ homepageLinks[curImg][m] +'"'+ target +' />';
									}
									$('#hero-map').html(maps);
								} else { // Just one link
									var target = (homepageLinks[curImg].toString().indexOf('http')!=-1) ? 'target="_blank"' : '';
									$('#hero-map').html('<area shape="rect" coords="0,0,959,336" href="'+ homepageLinks[curImg] +'"'+ target +' />');
								}
								
								
								heroTimer = setTimeout("$.nextImg()",time); // Added back in for Featured Rotation removal
							}
						}
					);
				}
			}
			// === FEATURED ROTATION =============
			return false;
			// Find next image number
			nextFeaturedImg = curFeaturedImg<(totalFeaturedImgs-1) ? curFeaturedImg+1 : 0;
			// Make sure the next image is preloaded
			if(eval('featuredImg'+nextFeaturedImg) != 1 && eval('img'+nextImg) != 1){
				// If images aren't preloaded yet, retry
				heroTimer = setTimeout("$.nextImg()",500);
			} else {
				// Setup next image
				
				// Handle possible external links
				if(homepageFeaturedLinks[nextFeaturedImg].indexOf("http")==0){
					var nextFeatured = $("<p id='nextFeaturedImg'><a href='"+homepageFeaturedLinks[nextFeaturedImg]+"' target='_blank'><img src='"+imgPath+homepageFeaturedImgs[nextFeaturedImg]+"' width='268' height='61' border='0' /></a></p>");
				} else {
					var nextFeatured = $("<p id='nextFeaturedImg'><a href='"+homepageFeaturedLinks[nextFeaturedImg]+"'><img src='"+imgPath+homepageFeaturedImgs[nextFeaturedImg]+"' width='268' height='61' border='0' /></a></p>");
				}
				
				
				$("#featuredImg").after(nextFeatured);
				// Start fading out current image and make the next image the current one
				// Image
				$("#featuredImg").animate({opacity: 0}, fadeSpeed,
					function(){
						$("#featuredImg").remove();
						$("#nextFeaturedImg").attr("id","featuredImg");
						curFeaturedImg = curFeaturedImg<(totalFeaturedImgs-1) ? nextFeaturedImg : 0;
						heroTimer = setTimeout("$.nextImg()",time);
					}
				);
			}
		}
		
		// Handle Hero Nav Links Click Event
		if($('#homepage_hero').length>0){
			$('.heroNav').live('click', function(){
				clearTimeout(heroTimer);
				clearTimeout(navTimer);
				var goto = $(this).attr('id').substring(7);
				// If hero is already showing and $.nextImg() is stopped...
				if(continueRunning==false && goto==curImg+1){return;}
				// If hero is already showing and $.nextImg() is not stopped...
				else if(continueRunning==true && goto==curImg+1){
					continueRunning = false;
					// Nav
					$(".heroNav").removeClass("active");
					$("#heroNav"+goto).addClass("active");
					// Image
					$("#nextHeroImg").remove();
					$("#heroImg").stop().css("opacity",1);
					curImg = goto-1;
					return;
				}
				// Stop $.nextImg()
				continueRunning = false;
				// Setup new image over current image
				eval('var newHeroImg'+goto+' = $("<div class=\'newHeroImg\' id=\'newHeroImg'+goto+'\'><img src=\''+imgPath+homepageImgs[(goto-1)]+'\' width=\'959\' height=\'336\' border=\'0\' usemap=\'#hero-map\' /></div>")');
				eval('newHeroImg'+goto+'.appendTo($("#homepage_hero")).css("opacity",0)'); //$("#heroImg").before(newHeroImg);
				// Stop other animations
				$("#heroImg").stop();
				// Change Nav
				$(".heroNav").removeClass("active");
				$("#heroNav"+goto).addClass("active");
				// Fade in image
				$("#newHeroImg"+goto).animate({opacity:1}, fadeSpeed/5, function(){
					$("#heroImg").stop().remove();
					$("#nextHeroImg").remove();
					$("#newHeroImg"+goto).attr("id","heroImg").removeClass("newHeroImg");
					curImg = goto-1;
					
					// Set Image Map
					if(homepageLinks[curImg].length > 1){ // More than one link
						var maps = '';
						for(var m=0; m<homepageLinks[curImg].length; m++){
							var target = (homepageLinks[curImg][m].toString().indexOf('http')!=-1) ? 'target="_blank"' : '';
							var shape  = (homepageCoords[curImg][m].split(',').length == 4) ? 'rect' : 'poly';
							maps += '<area shape="'+ shape +'" coords="'+ homepageCoords[curImg][m] +'" href="'+ homepageLinks[curImg][m] +'"'+ target +' />';
						}
						$('#hero-map').html(maps);
					} else { // Just one link
						var target = (homepageLinks[curImg].toString().indexOf('http')!=-1) ? 'target="_blank"' : '';
						$('#hero-map').html('<area shape="rect" coords="0,0,959,336" href="'+ homepageLinks[curImg] +'"'+ target +' />');
					}
				});
				
				// Restart Featured Rotation
				heroTimer = setTimeout("$.nextImg()",time);
				
				return false;
			});
		}
	});
	
	
	// Preload images based on array 'homepageImgs'
	function preloadImgs(w){
		for(var i=w; i<homepageImgs.length; i++){
			var preload = new Image();
			preload.src = imgPath+homepageImgs[i];
			if (preload.complete) {
				eval('img'+i+' = 1');
			} else {
				preload.onload = function() {
					eval('img'+i+' = 1');
					preloadImgs(i+1);
				};
				break;
			}
		}
	}
	// Preload images based on array 'homepageFeaturedImgs'
	function preloadFeaturedImgs(w){
		for(var i=w; i<homepageFeaturedImgs.length; i++){
			var preload = new Image();
			preload.src = imgPath+homepageFeaturedImgs[i];
			if (preload.complete) {
				eval('featuredImg'+i+' = 1');
			} else {
				preload.onload = function() {
					eval('featuredImg'+i+' = 1');
					preloadImgs(i+1);
				};
				break;
			}
		}
	}// ENDS: ROTATING HOME HERO PHOTO









    //******************************************
    // GLOBAL PAGE SCRIPTS
    //******************************************

    // Handle Breadcrumbs
    //===================
    // Turned off for now...
    //jQuery("#breadCrumb").jBreadCrumb();





    // CTA (Call to Action) Button Rollover
    //=====================================
    // Preload Images
    $("a img[src*='images/button_'],a img[src*='images/header_sign'], .CTA").each(function() {
        if (this.tagName.toLowerCase() == "img") {
            var src = $(this).attr("src");
            if (src.indexOf("_over") == -1) {
                src = src.split(".");
                $('<img />').attr('src', src[0] + "_over." + src[1]).load(function() { });
            }
        } else if (this.tagName.toLowerCase() == "input") {
            var bgImg = $(this).css("background-image");
            if (bgImg != "") {
                bgImg = bgImg.substring(4, bgImg.indexOf(")"));
                if (bgImg.indexOf("_over") == -1) {
                    var src = bgImg.substring(0, bgImg.lastIndexOf("."));
                    var ext = bgImg.substring(bgImg.lastIndexOf("."));
                    $('<img />').attr('src', src + "_over" + ext).load(function() { $(this).remove(); });
                }
            }
        }
    })
    // Handle Mouseover and Mouseout
    $("a img[src*='images/button_'],a img[src*='images/header_sign'], .CTA").live("mouseover", function() {
        // Determine if this is a IMG or INPUT with a CSS background image
        if (this.tagName.toLowerCase() == "img") {
            var src = $(this).attr("src");
            if (src.indexOf("_over") == -1) {
                src = src.split(".");
                $(this).attr("src", src[0] + "_over." + src[1]);
            }
        } else if (this.tagName.toLowerCase() == "input") {
            var bgImg = $(this).css("background-image");
            if (bgImg != "") {
                bgImg = bgImg.substring(4, bgImg.indexOf(")"));
                if (bgImg.indexOf("_over") == -1) {
                    var src = bgImg.substring(0, bgImg.lastIndexOf("."));
                    var ext = bgImg.substring(bgImg.lastIndexOf("."));
                    $(this).css("background-image", "url(" + src + "_over" + ext + ")");
                }
            }
        }
    }).live("mouseout", function() {
        if (this.tagName.toLowerCase() == "img") {
            var src = $(this).attr("src");
            if (src.indexOf("_over") != -1) {
                src = src.replace("_over", "");
                src = src.split(".");
                $(this).attr("src", src[0] + "." + src[1]);
            }
        } else if (this.tagName.toLowerCase() == "input") {
            var bgImg = $(this).css("background-image");
            if (bgImg != "") {
                bgImg = bgImg.substring(4, bgImg.indexOf(")"));
                if (bgImg.indexOf("_over") != -1) {
                    var src = bgImg.substring(0, bgImg.lastIndexOf(".") - 5);
                    var ext = bgImg.substring(bgImg.lastIndexOf("."));
                    $(this).css("background-image", "url(" + src + ext + ")");
                }
            }
        }
    });








    // Offsite Links
    //==============
    // Add class to all offsite links that don't contain a <span> or <img> (or uses image replacement technique)
    links = $("a[target='_blank'][rel!='pdf']:not([href^='/']):not([rel*='noIcon']):not(:has(span):has(img))");
    if (links.length > 0) {
        links.each(function() {
            // Get the text of each link and trim any whitespace
            var contents = jQuery.trim($(this).html());
            // Split into an array
            var a = contents.split(/\s/);
            // Wrap the last word in a span tag
            a[a.length - 1] = "<span class='offsiteLink'>" + a[a.length - 1] + "</span>";
            // Join the array back together and update the html text of the link
            $(this).html(a.join(" "));
        });
    }
    //$("a[target='_blank'][rel!='pdf']:not(:has(span):has(img))").addClass("offsiteLink");
	
    // Prepare for external links in disclaimer overlay
    $(".offsite").live("click", function(e) {
        e.preventDefault();
        if ($("#dontShowOffsiteWarn").attr("checked") == true) {
            createCookie("noOffsiteLinkWarning", true);
        }
        if ($.browser.msie) {
            $("#overlay").remove();
            $(".coverupClear").remove();
        } else {
            $("#overlay").fadeOut("normal", function() {
                $("#overlay").remove();
            });
            $(".coverupClear").fadeOut("normal", function() {
                $(".coverupClear").remove();
            });
        }
		pageTracker._trackPageview('/out-bound-urls/'+ $(this).attr("href") );
        window.open($(this).attr("href"));
    });
    // Trigger handler for all offsite links with target=_blank  (Added map areas to selector for homepage hero multiple links on 11/17/11)
    $("a[target='_blank'][rel!='pdf']:not([href^='/']):not([rel*='notOffsite']):not([class='offsite']), map area[target='_blank']").live("click", function(e) {
        if (readCookie("noOffsiteLinkWarning") == null) {
            e.preventDefault();
            // If there's already a dialog box open, close it...
            if ($("#overlay").length > 0) {
                $("#overlay").remove();
                $(".coverupClear").remove();
            }

            // Find which item and content to add to overlay
			if ($(this).attr("rel") == "stateLink" || $(this).attr('href').indexOf('.tx.us')!=-1 || $(this).attr('href').indexOf('.gov')!=-1) {
                var offsiteLinkCopy = "<h3>External Link</h3><p>You are now leaving TravelTex.com. You are on your way to an external website.</p> \
				<p style='padding:0;'><a href='" + $(this).attr("href") + "' class='offsite' target='_blank'>Continue to external website.</a></p> \
				<fieldset style='padding-bottom:1.3em;'> \
					<input type='checkbox' id='dontShowOffsiteWarn' /><label for='dontShowOffsiteWarn' style='font-size:1.1em; color:#888;'>Don't show this warning again.</label> \
				</fieldset> \
				<p><a href='" + $(this).attr("href") + "' class='closeLink'>Don&rsquo;t go to external website. Stay on TravelTex.com.</a><br /></p> \
				";
            } else {
                var offsiteLinkCopy = "<h3>External Link</h3><p>You are now leaving TravelTex.com. You are on your way to an external website.</p> \
				<p>Economic Development &amp; Tourism (EDT) provides these links solely for the convenience of our visitors and does not endorse, operate or control the external websites. EDT cannot be liable for direct or indirect damage to the user resulting from Internet connections, including but not limited to viruses, pop ups, spyware, or offensive materials.</p> \
				<p style='padding:0;'><a href='" + $(this).attr("href") + "' class='offsite' target='_blank'>Continue to external website.</a></p> \
				<fieldset style='padding-bottom:1.3em;'> \
					<input type='checkbox' id='dontShowOffsiteWarn' /><label for='dontShowOffsiteWarn' style='font-size:1.1em;'>Don't show this warning again.</label> \
				</fieldset> \
				<p><a href='" + $(this).attr("href") + "' class='closeLink'>Don&rsquo;t go to external website. Stay on TravelTex.com.</a><br /></p> \
				";
            }

            // Create Overlay DIV and background Overlay DIV
            var coverup = $("<div/>").attr("class", "coverupClear");
            var olDiv = $("<div/>").attr("id", "overlay").attr("class", "overlayA");
            $("body").append(coverup);
            $("body").append(olDiv);

            //Create Close button for DIV and Cover Up
            $("#overlay").append("<span id='overlayClose'><a href='#' title='Close'></a></span>");
            $("#overlayClose a, .coverupClear, .closeLink").live("click", function(e) {
                e.preventDefault();
                if ($.browser.msie) {
                    $("#overlay").remove();
                    $(".coverupClear").remove();
                } else {
                    $("#overlay").fadeOut("normal", function() {
                        $("#overlay").remove();
                    });
                    $(".coverupClear").fadeOut("normal", function() {
                        $(".coverupClear").remove();
                    });
                }
            });

            // Populate Overlay
            $("#overlay").append('<div class="ol_top"></div><div class="ol_mid clearfix">' + offsiteLinkCopy + '</div><div class="ol_bot"></div>');

            // Position and Reveal Overlay and Coverup
            $.positionDiv("#overlay");
            if ($.browser.msie) {
                $(".coverupClear").css("display", "block");
                $("#overlay").css("display", "block");
            } else {
                $(".coverupClear").fadeIn();
                $("#overlay").fadeIn();
            }
        }
    });



    // PDF Download Links
    //===================
    // Add class to all PDF links that don't contain a <span> (or uses image replacement technique)
    $("a[rel='pdf']:not(:has(span))").addClass("pdfLink");


    // YouTube Flash Plugin for TexasVideos
    //=====================================
    //$('a[href^="http://www.youtube.com"]').flash({ width: 560, height: 340 }, { version: 8 }, function(htmlOptions) { $this = $(this); htmlOptions.src = $this.attr('href'); $this.before($.fn.flash.transform(htmlOptions)); });
    $('a[href^="http://www.youtube.com"]:not(#home-accordion a)').each(function() {
        // Make sure the user has flash installed...
        if ($(this).flash.hasFlash.playerVersion() != null) {
            var src = $(this).attr("href").replace("watch?v=", "v/") + "?feature=player_embedded&rel=0&fs=1"; //switch out url
            var w = $(this).attr("rel").split(",").splice(0, 1);
            var h = $(this).attr("rel").split(",").splice(1, 1);
            var embed = '<object width="' + w + '" height="' + h + '"> \
						<param value="' + src + '" name="movie"/> \
						<param value="true" name="allowFullScreen"/> \
						<param value="wmode" name="transparent"/> \
						<embed width="' + w + '" height="' + h + '" allowfullscreen="true" wmode="transparent" type="application/x-shockwave-flash" src="' + src + '"/> \
						</object>';
            $(this).before(embed);
            $(this).remove();
        }
    });


    // Commercial Videos
    //===================
    $(".commFlash").each(function() {
        //var video = $(this).attr("class").split(' ')[1];
        var video = $(this).attr("id");

        //var so = new SWFObject("/flash/player.swf?videoFile=tv_flv/A_Texas_Moment_60_SD&looping=true&sound=true&videoLength=60.3", "flash_tv", "515", "400", "7", "#FFFFFF");


        $(this).flash({
            src: '/flash/player.swf?videoFile=' + video,
            width: 515,
            height: 400,
            name: "flash_tv"
        },
					  { update: false, version: 7 });
    });




    // Add "Labels" to form fields
    //============================
    var inputs = [];
    inputs["#global_search_keywords"] = "Enter Keyword(s)";
    inputs["#global_search_keywords2"] = "Enter Keyword(s)";
    inputs["#emailNewsletter_email"] = "your e-mail address";
    inputs[".optional"] = "optional";
    inputs[".optionalPhone"] = "optional (ex. 555-555-5555)";
    inputs[".phone1"] = "ex. 214-555-1845";
    inputs[".phone2"] = "ex. 214-555-1845";
    inputs[".webaddy"] = "ex. http://www.yoursite.com";
    inputs["#ttdSearchTxt"] = "Attractions and Events";
    inputs["#attractionSearchTxt"] = "Search for Attractions";
    inputs["#eventSearchTxt"] = "Search for Events";
    inputs["#citySearchTxt"] = "Search for a City";

    // Set form field values based on array above
    for (i in inputs) {
        for (var q = 0; q < $(i).length; q++) {
            // Make sure the form fields don't already have a set value
            if ($("#" + $(i)[q].id).val().length == 0) {
                $("#" + $(i)[q].id).attr("value", inputs[i]);
            } else {
                if ($("#" + $(i)[q].id).val() != inputs[i]) {
                    $("#" + $(i)[q].id).removeClass("optional");
                }
            }
        }
        $(i).attr("value", inputs[i]);
    };

    // Clear form fields' value when in focus and return when blurred
    $("input, textarea").each(function() {
        $(this).focus(function() {
            var id = "#" + $(this).attr("id"); // Grab IDs
            var c = $(this).attr("class").split(" "); // Grab ClassNames
            for (var a = 0; a < c.length; a++) { // Prep ClassNames to have "."
                c.splice(a, 1, "." + c[a])
            }
            for (i in inputs) {
                // Look for it via ID
                if (i == id) {
                    if ($(this).attr("value").toLowerCase() == inputs[id].toLowerCase()) {
                        $(this).attr("value", "");
                    }
                } else {
                    // Look for it via classname
                    for (var l = 0; l < c.length; l++) {
                        if (i == c[l]) {
                            if ($(this).attr("value").toLowerCase() == inputs[c[l]].toLowerCase()) {
                                $(this).attr("value", "");
                                $(this).addClass("optionalTxt");
                            }
                        }
                    }
                }
            }
        });
        $(this).blur(function() {
            var id = "#" + $(this).attr("id"); // Grab IDs
            var c = $(this).attr("class").split(" "); // Grab ClassNames
            for (var a = 0; a < c.length; a++) { // Prep ClassNames to have "."
                c.splice(a, 1, "." + c[a])
            }
            for (i in inputs) {
                // Look for it via ID
                if (i == id) {
                    if ($(this).attr("value") == "") {
                        $(this).attr("value", inputs[id]);
                    }
                } else {
                    // Look for it via classname
                    for (var l = 0; l < c.length; l++) {
                        if ($(this).attr("value") == "") {
                            $(this).attr("value", inputs[c[l]]);
                            $(this).removeClass("optionalTxt");
                        }
                    }
                }
            }
        });
    }); // End







    // Sign In Overlay Box
    //====================
    // Position it after the SignIn button
    $("#gs_container").after($("#signinBox"));
    // Handle Sign In button trigger
    $("#signin").click(function(e) {
        e.preventDefault();
        // Create DIV Coverup to prevent clicking things in the background
        /*var coverup = $("<div class='signinCoverup' />");
        coverup.css({position:'fixed', zIndex:'899', left:'0', top:'0', width:'100%', height:'100%' });
        $("body").append(coverup);
        $(".signinCoverup").click(function(){
        $(".signinCoverup").remove();
        $("#signinBox").fadeOut("fast");
        });
        $(coverup).fadeIn("normal");*/
        
		// If sign in box was positioned with "fixed" (see function launch_planner())
		if($("#signinBox").css("display")=="block"){
			$("#signinBox").removeClass("fixedPos").css({right: 17, top: 75, left: 'auto'});
			return;
		}
		
		
		if ($.browser.msie) {
            if ($("#signinBox").css("display") == "none") {
                $("#signinBox").css("display", "block");
                $("#signinEmail").focus();
            } else {
                $("#signinBox").css("display", "none");
            }
        } else {
            if ($("#signinBox").css("display") == "none") {
                $("#signinBox").fadeIn("normal", function() {
                    $("#signinEmail").focus();
                });
            } else {
                $("#signinBox").fadeOut("fast");
            }
        }
    });
    // Handle Sign In Cancel button trigger
    $("#signinBox .cancelButton").click(function(e) {
        e.preventDefault();
        //$(".signinCoverup").remove();
        if ($.browser.msie) {
            $("#signinBox").css("display", "none");
			// If sign in box was positioned with "fixed" (see function launch_planner())
			if($("#signinBox").attr("class").indexOf("fixedPos")!=-1){
				$("#signinBox").removeClass("fixedPos").css({right: 17, top: 75, left: 'auto'});
				// Put back into header if it was opened from Trip Planner
				if(signInFromTripPlanner == 1){
					$("#signinBox").appendTo($("#header")).css("z-index",900);
					signInFromTripPlanner = 0;
					$("#openTripPlanner").attr("value",false);
				}
			}
        } else {
            $("#signinBox").fadeOut("fast", function(){
				// If sign in box was positioned with "fixed" (see function launch_planner())
				if($("#signinBox").attr("class").indexOf("fixedPos")!=-1){
					$("#signinBox").removeClass("fixedPos").css({right: 17, top: 75, left: 'auto'});
					// Put back into header if it was opened from Trip Planner
					if(signInFromTripPlanner == 1){
						$("#signinBox").appendTo($("#header")).css("z-index",900);
						signInFromTripPlanner = 0;
						$("#openTripPlanner").attr("value",false);
					}
				}
			});
        }
	});





    // Handle Text Resizing Button
    //============================
    $(".textsize a").click(function(e) {
        e.preventDefault();
        if ($("link#largeFont").attr("disabled") == true) {
            $("link#largeFont").attr("disabled", false);
            createCookie("css", false);
            $(".textsize a").css("background-position", "0 -22px");
        } else {
            $("link#largeFont").attr("disabled", true);
            createCookie("css", true);
            $(".textsize a").css("background-position", "0 0");
        }
    });
    // If there's a cookie set already, read and set CSS text size... else just show normal text size
    if (readCookie("css")) {
        var cookieVal = readCookie("css");
        $('head').append('<link rel="stylesheet" type="text/css" href="css/largeFont.css" id="largeFont" media="screen" disabled="disabled"></link>');
        if (cookieVal == "true") { $("link#largeFont").attr("disabled", true); }
        if (cookieVal == "false") { $("link#largeFont").attr("disabled", false); }
    } else {
        $('head').append('<link rel="stylesheet" type="text/css" href="css/largeFont.css" id="largeFont" media="screen" disabled="disabled"></link>');
        $("link#largeFont").attr("disabled", true);
    }




    // Generic "show overlay" div with some content
    //=============================================
    // To Use, add link: <a href="#" class="showOverlay" rel="contentID">LINK</a>
    // Add content to hidden element: <div id="contentID" class="hidden">CONTENT</div>
    // The "rel" in the link and the content's "id" must match.

    //$(".showOverlay").each(function() {
    $(".showOverlay").live("click", function(e) {
        e.preventDefault();
        // Remove any other Overlays
        if ($("#overlay").length > 0) {
            $("#overlay").remove();
            $(".coverupClear").remove();
        }

        // Find which item and content to add to overlay
        var whichItem = $(this).attr("rel");

        // Create Overlay DIV and background Overlay DIV
        var whichOverlay = "overlayA";
        var classes = $(this).attr('class').split(' ');
        
        for ( j in classes )
        {
           if (classes[j].indexOf("showOverlay_565") > -1) { whichOverlay = "overlay_565"; }
        }
        
        var coverup = $("<div/>").attr("class", "coverupClear");
        var olDiv = $("<div/>").attr("id", "overlay").attr("class", whichOverlay);
        $("body").append(coverup);
        $("body").append(olDiv);

        //Create Close button for DIV and Cover Up
        $("#overlay").append("<span id='overlayClose'><a href='#' title='Close'></a></span>");
        $("#overlayClose a, .coverupClear").click(function(e) {
            e.preventDefault();
            if ($.browser.msie) {
                $("#overlay").remove();
                $(".coverupClear").remove();
            } else {
                $("#overlay").fadeOut("normal", function() {
                    $("#overlay").remove();
                });
                $(".coverupClear").fadeOut("normal", function() {
                    $(".coverupClear").remove();
                });
            }
        });

        // Populate Overlay
        $("#overlay").append('<div class="ol_top"></div><div class="ol_mid clearfix">' + $('#' + whichItem).html() + '</div><div class="ol_bot"></div>');

        // Position and Reveal Overlay and Coverup
        $.positionDiv("#overlay");
        if ($.browser.msie) {
            $(".coverupClear").css("display", "block");
            $("#overlay").css("display", "block");
        } else {
            $(".coverupClear").fadeIn();
            $("#overlay").fadeIn();
        }
    });



    // Truncator: Truncates copy and adds a "read more" link
    //======================================================
    if ($('.truncate').length > 0) {
        $('.truncate').truncate({ max_length: 370 });
    }
    if ($('.truncate250').length > 0) {
        $('.truncate250').truncate({ max_length: 250 });
    }
    if ($('.truncate150').length > 0) {
        $('.truncate150').truncate({ max_length: 150 });
    }



    // Download Screensavers Preview
    //==============================
    // Removed per TM's request 12/3/09
    /*$(".screensavers .item p img").mouseover(function() {
    $(this).attr("src", $(this).attr("src").substr(0, $(this).attr("src").lastIndexOf(".") + 1) + "gif");
    }).mouseout(function() {
    $(this).attr("src", $(this).attr("src").substr(0, $(this).attr("src").lastIndexOf(".") + 1) + "jpg");
    });*/




    // Help FAQs Section
    //==================
	$("ol.help ul").hide();
    $("ol.help li a").click(function(e) {
        e.preventDefault();
        $(this).parent().find("ul").fadeIn()
    });



    // Lodging Sidebar & Home Search
    if ($("p.lodgingSidebarButton a").length > 0 || $('p.home-lodgingButton a').length > 0) {
        $("p.lodgingSidebarButton a, p.home-lodgingButton a").click(function(e) {
            if($(this).attr('href') == '#'){
				e.preventDefault();
				var home = $(this).parent().attr('class').indexOf('home')!=-1 ? true : false;
				
				var cloneID = 88;
				var groupID = (home == false) ? $(".lodgingCitySearch #city").val() : $(".home-lodgingCitySearch #city").val();
				var lodgingID = (home == false) ? $(".lodgingCitySearch #type").val() : $(".home-lodgingCitySearch #type").val();
				var startDate = (home == false) ? $(".lodgingDatesSearch #checkIn").val() : $(".home-lodgingDatesSearch #checkIn").val();
				var endDate = (home == false) ? $(".lodgingDatesSearch #checkOut").val() : $(".home-lodgingDatesSearch #checkOut").val();
				//|| {
				if (groupID == "" || lodgingID == "") 
				{ 
					$(".lodgingError").html("<p>Please provide a city.</p>");
				} 
				else if ((startDate != "" && endDate == "") || (startDate == "" && endDate != ""))
				{
					$(".lodgingError").html("<p>Both Check-In and Check-Out dates are required.</p>");
				}
				else
				{ 
					$(".lodgingError").html("");
					location.href = "http://texas-trips.com/booking_results.php?start-date=" + startDate + "&end-date=" + endDate + "&lodgingID=" + lodgingID + "&cloneID=88&group_id=" + groupID;
				}
			}
        });
    }







    //******************************************
    // SEARCH & REGION SELECTION SCRIPTS
    //******************************************

    // Autocomplete on Search
    //=======================
    //	$("#global_search_keywords").autocomplete("http://new.traveltex.com/sayt.aspx",{autoFill:true,width:205,minChars:2});
    $("#citySearchTxt").autocomplete("/sayt.aspx", { autoFill: false, selectFirst:false, width: 560, minChars: 2, extraParams: { t: "City"} });
    $("#attractionSearchTxt").autocomplete("/sayt.aspx", { autoFill: false, selectFirst:false, width: 560, minChars: 2, extraParams: { t: "Attraction"} });
    $("#eventSearchTxt").autocomplete("/sayt.aspx", { autoFill: false, selectFirst:false, width: 560, minChars: 2, extraParams: { t: "Event"} });
    $("#ttdSearchTxt").autocomplete("/sayt.aspx", { autoFill: false, selectFirst:false, width: 560, minChars: 2, extraParams: { t: "AttractionEvent"} });
    $(".weatherSearchTxt").autocomplete("/sayt.aspx", { autoFill: false, selectFirst:false, width: 560, minChars: 2, extraParams: { t: "City"} });

    $("#global_search_keywords").autocomplete("/sayt.aspx", { autoFill: false, selectFirst:false, width: 287, minChars: 2, extraParams: { } });
    $("#global_search_keywords2").autocomplete("/sayt.aspx", { autoFill: false, selectFirst:false, width: 287, minChars: 2, extraParams: { } });
    
    
    $(".advSearchCityField").unautocomplete().autocomplete("/sayt.aspx", { cacheLength: 1, autoFill: false, selectFirst:false, width: 287, minChars: 2, extraParams: { t: "City", r: function(){ return $("select.region option:selected").text();} } });
    $(".advSearchKeywordField").autocomplete("/sayt.aspx", { autoFill: false, selectFirst:false, width: 287, minChars: 2 });

    // Show Advanced Search Options
    //=============================
    $(".advSearch .types").change(function() {
        $(".advSearchOptions").hide(); // hide all of them first
        $(".category").val(""); // set categories to empty first
        $(".subcategory").hide(); // hide subcategories
        $(".subcategory").val(""); // set subcategories to empty first

        $(".begDate, .endDate").val(""); // Clear the date fields

        // Get selected category
        var selected = $(this.options[this.selectedIndex]).text().toLowerCase();
        if (selected != "") {
            // We want just the first word of the category name
            if (selected.indexOf(" ") != -1) {
                selected = selected.substr(0, selected.indexOf(" "));
            }
            // Reveal more options for this category
            $("#" + selected +"Container").fadeIn();
        }
    });

    // If the dropdown is preselected on page load
    if ($(".advSearch .types :selected").text() != "") {
        var selected = $(".advSearch .types :selected").text().toLowerCase();
        if (selected != "") {
            // We want just the first word of the category name
            if (selected.indexOf(" ") != -1) {
                selected = selected.substr(0, selected.indexOf(" "));
            }
            // Reveal more options for this category
            $("#" + selected +"Container").show();
        }
    }

    // Show Advanced Search SubCategories
    $(".category").change(function() {
        $(".subcategory").hide(); // hide all of them first
        $(".subcategory").val(""); // set all of them to empty first

        // Get selected category
        var selected = $(this.options[this.selectedIndex]).val().toLowerCase();
        var itemtype = $(this).attr("id");
        if (selected != "") {
            // Reveal more options for this category
            $("#" + itemtype + "-" + selected).fadeIn();
        }
    });
    // If the dropdown is preselected on page load
    $(".category :selected").each(function(){
        if($(this).val() != ""){
            var selected = $(this).val().toLowerCase();
            var itemtype = $(this).parent().attr("id");
            if (selected != "") {
                // Reveal more options for this category
                $("#" + itemtype + "-" + selected).show();
            }
        }
    });


	// Advanced Search Tips
	if($('fieldset.advSearch').length>0){
		$(this).find('a[href=#searchTips]').click(function(){
			// If there's already a dialog box open, close it...
			if ($("#overlay").length > 0) {
				$("#overlay").remove();
				$(".coverupClear").remove();
			}
	
			// Create Overlay DIV and background Overlay DIV
			var coverup = $("<div/>").attr("class", "coverupClear");
			var olDiv = $("<div/>").attr("id", "overlay").attr("class", "overlayA searchTips");
			$("body").append(coverup);
			$("body").append(olDiv);
	
			//Create Close button for DIV and Cover Up
			$("#overlay").append("<span id='overlayClose'><a href='#' title='Close'></a></span>");
			$("#overlayClose a, .coverupClear, .closeLink").live("click", function(e) {
				e.preventDefault();
				if ($.browser.msie) {
					$("#overlay").remove();
					$(".coverupClear").remove();
				} else {
					$("#overlay").fadeOut("normal", function() {
						$("#overlay").remove();
					});
					$(".coverupClear").fadeOut("normal", function() {
						$(".coverupClear").remove();
					});
				}
			});
			
			// Populate Overlay
			var searchTips = $('#searchTips').html();
			$("#overlay").append('<div class="ol_top"></div><div class="ol_mid clearfix">' + searchTips + '</div><div class="ol_bot"></div>');
	
			// Position and Reveal Overlay and Coverup
			$.positionDiv("#overlay");
			if ($.browser.msie) {
				$(".coverupClear").css("display", "block");
				$("#overlay").css("display", "block");
			} else {
				$(".coverupClear").fadeIn();
				$("#overlay").fadeIn();
			}
		});
	}


    // Datepicker for Events 
    //======================
    if ($("input.begDate").length > 0) {
		$("input.begDate").datepick({
			showOn: 'both',
			buttonImageOnly: true,
			buttonImage: 'images/cal_icon.gif',
			minDate: 0,
			onSelect: function(dateText, inst){
				$("input.endDate").datepick('option', 'minDate', new Date(inst.setDate(inst.getDate()+1)));
			}
		});
	}
    if ($("input.endDate").length > 0) { $("input.endDate").datepick({ showOn: 'both', buttonImageOnly: true, buttonImage: 'images/cal_icon.gif', minDate: ($("input.begDate").length>0?new Date($("input.begDate").val()):0) }); }
    if ($("input.eventDate").length > 0) { $("input.eventDate").datepick({ multiSelect: 999, showOn: 'both', buttonImageOnly: true, buttonImage: 'images/cal_icon.gif' }); }
    $(".datepicker a[rel]").click(function(e) {
        e.preventDefault();
        $("." + $(this).attr("rel")).val("");
    });


    // Datepicker for Lodging
    //=======================
    if ($(".lodgingEventDate").length > 0) { $(".lodgingEventDate").datepick({ showOn: 'both', buttonImageOnly: true, buttonImage: 'images/cal_icon.gif' }); }
	





    // Search Region Dropdown
    //=======================
    // Add Replacement code to page
    if (typeof regionsReplacement != 'undefined') {
        $(".region").after(regionsReplacement);
    }

    // Hide orig dropdown and get any pre-selected value
    if ($(".region").length > 0) {
        $(".region").css("display", "none");
        var curReg = $(".region").val();
        if (curReg != "") {
            $.changeRegions(curReg);
            $.highlightLI(curReg);
            $(".regionsSelect p.fauxDropDown a").text($("#regionAlt ul li." + curReg).text())
        }
    }
    //Preload images first...
    var regions = ["bigBend", "gulfCoast", "hillCountry", "panhandlePlains", "pineyWoods", "prairiesLakes", "southTexasPlains"]
    if ($("p.map").length > 0) {
        for (x in regions) { $.preloadImages("images/region_map_" + regions[x] + ".jpg"); }
    }
    // Handle Trigger to show "drop down"
    $(".regionsSelect p.fauxDropDown a").bind("click focus", function(e) {
        e.preventDefault();
        // In case the user clicks outside of the Regions DIV, close the DIV...
        var regionsCoverup = $("<div/>").attr("id", "regionsCoverUp");
        regionsCoverup.css({
            position: "absolute",
            left: 0,
            top: 0,
            width: "100%",
            height: "100%",
            display: "block",
            zIndex: "1001"
        })
        regionsCoverup.click(function() {
            $("#regionAlt").css("display", "none");
            $("#regionsCoverUp").remove();
        });
        $("body").prepend(regionsCoverup);
        // Show Regions DIV		
        $("#regionAlt").css("display", "block");

    });
    // Setup MouseOver and Click Triggers for Map
    $("#region_map area").each(function() {
        $(this).mouseover(function() {
            $.changeRegions(this.id);
            $.highlightLI(this.id);
        });
        $(this).mouseout(function() {
            $.changeRegions(0);
            $.unhighlightLI(this.id);
        });
        $(this).click(function(e) {
            e.preventDefault();
            $("#regionAlt").css("display", "none");
            $(".region").val(this.id);
            $(".regionsSelect p.fauxDropDown a").text($("#regionAlt ul li." + this.id).text());
			// Clear AutoComplete Cache on Adv Search
			/*if($(".advSearchCityField").length > 1){
				$(".advSearchCityField").flushCache();
			}*/
        });
    });
    // Setup MouseOver and Click Triggers for LI Links
    $("#regionAlt ul li a").each(function() {
        $(this).mouseover(function() {
            var classNme = $(this).parent().get(0).className
            $.highlightLI(classNme);
            if (classNme == "all") { classNme = 0; }
            $.changeRegions(classNme);

        });
        $(this).mouseout(function() {
            $.changeRegions(0);
            var classNme = $(this).parent().get(0).className.split(" ").slice(0, 1).toString();
            $.unhighlightLI(classNme);
        });
        $(this).click(function(e) {
            e.preventDefault();
            $("#regionAlt").css("display", "none");
            var classNme = $(this).parent().get(0).className.split(" ").slice(0, 1).toString();
            if (classNme == "all") { $(".region").val(""); }
            else { $(".region").val(classNme); }
            $(".regionsSelect p.fauxDropDown a").text($("#regionAlt ul li." + classNme).text())
        });
    });

    // Explore Regions Map
    //====================
    // Setup MouseOver and Click Triggers for Map
    var curExpRegion = "";
    $("#region_map_explore area").each(function() {
        if (this.className == "active") {
            curExpRegion = this.id;
            $.changeRegions(this.id);
        }

        $(this).mouseover(function() {
            $.changeRegions(this.id)
        });
        $(this).mouseout(function() {
            // Trigger MouseOut but check to see if any region has been selected
            if (curExpRegion == "") {
                $.changeRegions(0);
            } else {
                $.changeRegions(curExpRegion);
            }
        });
        $(this).click(function(e) {
            e.preventDefault();
            // Reset rotating weather
            if (curExpRegion != "") {
                $.clearRotatingWeather();
            }
            // Set the current region
            curExpRegion = this.id;
            // Change the image
            $.changeRegions(this.id);
            // Show region content & hide intro copy
            $("div.intro").hide();


            $("div.regCopy").each(function() {
                $(this).css("display", "none");
            });
            $("div.regCopy").each(function() {
                if (this.className.split(" ").splice(0, 1) == curExpRegion) {
                    //$(this).css("display","block");
                    $(this).fadeIn("normal");
                    $("." + curExpRegion + "2").fadeIn("normal");
                    $("." + curExpRegion + "Clear").css("display", "block");
                }
            });
        });
    });
    // Pick a random region to display automatically
    var randRegion = Math.floor(Math.random() * regions.length);
    $(".regionMapContent #" + regions[randRegion]).trigger("click");



    // Rotating Region Weather
    //========================
    if ($(".bigRegionWeather").length > 0 || $(".smallWeatherContainer").length > 0) {
        var curCity = 1; var timer = 8000;
        var t = setTimeout("$.rotateWeather()", timer);
    }
    $.rotateWeather = function() {
        var time = 400;
        if (curCity == 1) {
            $(".city1").fadeOut(300); t = setTimeout("$.rotateWeather2(2)", time);
        }
        else if (curCity == 2) {
            $(".city2").fadeOut(300); t = setTimeout("$.rotateWeather2(3)", time);
        }
        else if (curCity == 3) {
            $(".city3").fadeOut(300); t = setTimeout("$.rotateWeather2(1)", time);
        }
    }
    $.rotateWeather2 = function(w) {
        $(".city" + w).fadeIn(500);
        curCity = w;
        t = setTimeout("$.rotateWeather()", timer);
    }
    $.clearRotatingWeather = function() {
        clearTimeout(t);
        $(".city1").each(function() { $(this).css("display", "block"); })
        $(".city2, .city3").each(function() { $(this).css("display", "none"); })
        curCity = 1;
        t = setTimeout("$.rotateWeather()", timer);
    }




    //******************************************
    // TRIP PLANNER SCRIPTS
    //******************************************

	// Focus on Email field for Landing Page
	//======================================
	if($('#container #content #tpLanding fieldset .txtFields input').length > 0){
		$('#container #content #tpLanding fieldset .txtFields input:first').focus();
	}

    // Handle links to open Trip Planner
    //==================================
    $(".openTripPlanner").each(function() {
        $(this).click(function(e) {
            e.preventDefault();
            $("html, body").animate({ scrollTop: 0 }, 'normal');
            $.openTripPlanner();
        });
    });

    $.openTripPlanner = function(tripID) {
        // Is Trip Planner already open?
        if (tripPlannerOpen == 0) {
            //Create coverup DIV
            var coverup = $("<div/>").attr("class", "coverup");
            //Create DIV for Trip Planner to live
            var mydiv = $("<div/>").attr("id", "tripPlannerDiv");
            // Set the Flash Alt Content
            var copy = "<p style='font-family:\"Times New Roman\", Times, serif; font-size:3em; padding:100px'>In order to view the Trip Planner, you need to update to the latest version of the <a href='http://get.adobe.com/flashplayer/' target='_blank'>Adobe Flash plugin</a>.</p>";
            mydiv.html(copy);

            $("body").append(coverup);
            $("body").append(mydiv);
            //Create Close button for DIV
            //$("#tripPlannerDiv").append("<span id='overlayClose'><a href='#' title='Close'></a></span>");
            //$("#overlayClose a, .coverup").click(function(e) {
            /*$(".coverup").click(function(e) {
            e.preventDefault();
            $("#tripPlannerDiv").fadeOut("normal", function() {
            $("#tripPlannerDiv").remove();
            tripPlannerOpen = 0;
            });
            $(".coverup").fadeOut("normal", function() {
            $(".coverup").remove();
            });
            RefreshSidebar();
            });*/
            //Position DIV
            //$.positionDiv("#tripPlannerDiv")
            var l = ($(window).width() - $("#tripPlannerDiv").width()) / 2;
            $("#tripPlannerDiv").css("left", l).css("top", "10px");
            //If the User resizes the window, adjust the #container height
            $(window).bind("resize", function() {
                updatePosition("#tripPlannerDiv", 1)
            });


            // Fade in DIV
            $("#tripPlannerDiv").fadeIn("normal");
			// Check if there are any open actions needing passed to the flash
			if(typeof openTripPlannerActionVar != 'undefined'){var openAction = openTripPlannerActionVar;}
			else{var openAction = '';}
            //Embed Flash into DIV
            $('#tripPlannerDiv').flash(
				{
				    src: 'flash/tripPlannerShell.swf',
				    width: 965,
				    height: 605,
				    id: "tripPlannerFlash",
				    wmode: "opaque",
				    flashvars: { u: tpVars["userid"], t: (tripID != null ? tripID : tpVars["tripid"]), w: tpVars["wsdl"], k: tpVars["gkey"], n: tpVars["name"], s: openAction}
				},
				{ update: false,
				    version: '9.0.0'
				},
				function(htmlOptions) {
				    //htmlOptions.flashvars.txt = this.innerHTML;
				    //this.innerHTML = '<div>'+this.innerHTML+'</div>';
				    //var $alt = $(this.firstChild);
				    //htmlOptions.height = $alt.height();
				    //htmlOptions.width = $alt.width();
				    //$alt.addClass('alt');
				    $(this).css("background", "transparent");
				    $(this).find("p").remove();
				    $(this).addClass('flash-replaced').prepend($.fn.flash.transform(htmlOptions));
				}

			);

            tripPlannerOpen = 1;
        } // End: if(tripPlannerOpen==0)
    }


    // TRIP PLANNER LANDING PAGE
    //==========================
    $('#tripPlannerSwf').flash(
        {
            src: 'flash/landingLoader.swf',
            width: 959,
            height: 520,
            wmode: "opaque",
            id: "tripplannerLandingPg"
        },
        { update: true,
            version: '10.0.0'
        }
    );






    //******************************************
    // FORM SCRIPTS
    //******************************************




    // Contact Us Form: Show info when user selects a subject matter.
    //===============================================================
    $(".contactUs .subject").change(function() {
        // Remove any previous info
        $(".contactSubjInfo").remove();
        // Get the selected value
        var selected = $(this).val();
        // Find the classname of the selected Value
        var w = "";
        $(".contactUs .subject option").each(function() {
            if ($(this).val() == selected) {
                w = this.className;
            }
        });
        // If there is extra info, display it for the user
        if (w != "") {
            var info = $("<p/>").attr("class", "contactSubjInfo");
            $(".contactUs .subject").after(info);
            $(".contactSubjInfo").html($("li." + w).html());
            $(".contactSubjInfo").fadeIn();
        } else {
            $(".contactSubjInfo").remove();
        }
    });
    // See if the dropdown is already selected (say on page reload)
    // and if so, do the same as above. Need to combine this code.
    if ($(".contactUs .subject").length > 0) {
        var selected = $(".contactUs .subject").val(); var w = "";
        $(".contactUs .subject option").each(function() { if ($(this).val() == selected) { w = this.className; } });
        if (w != "") { var info = $("<p/>").attr("class", "contactSubjInfo"); $(".contactUs .subject").after(info); $(".contactSubjInfo").html($("li." + w).html()); $(".contactSubjInfo").fadeIn(); }
        else { $(".contactSubjInfo").remove(); }
    }
	
	


    // Generic Form Errors
    //====================
    if ($(".formErrors").length != 0) {
        $(".formErrors").addClass("hideFormErrors");
        $.positionDiv(".formErrors");
        var coverup = $("<div/>").attr("class", "coverup");
        $("body").append(coverup);
        //Create Close button and link for DIV
        $(".formErrors").append("<span id='overlayClose'><a href='#' title='Close'></a></span>");
        $("#overlayClose a, .coverup").click(function(e) {
            e.preventDefault();
            $(".formErrors").fadeOut("normal", function() {
                $(".formErrors").remove();
            });
            $(".coverup").fadeOut("normal", function() {
                $(".coverup").remove();
            });
        });
        var closeLink = $('<p class="closeErrors"><a href="#">Close and Fix Errors</a></p>')
        $(".formErrors").append(closeLink);


        $(".formErrors").fadeIn("slow")
        $(".formErrors p.closeErrors a").click(function(e) {
            e.preventDefault();
            $(".coverup").fadeOut("normal", function() {
                $(".coverup").remove();
            });
            $(".formErrors").fadeOut("fast", function() {
                $(".formErrors").remove();
            });
        });
    }
    $(".error").focus(function() {
        $(this).css("border", "1px solid #ccc");
    });




    // Show / Hide Advanced Search
    //============================
    //if ($('.advSearch')) $('.advSearch').hide();
    //if ($('a.advSearchOpen').click) {
    $('a.advSearchOpen').live("click", function(e) {
        e.preventDefault();
        $(this).text("Hide Search Options");
        $(this).removeClass("advSearchOpen").addClass("advSearchClose");
		$('.advSearch').fadeIn();
    });
    $('a.advSearchClose').live("click", function(e) {
        e.preventDefault();
        $(this).text("Refine Your Search");
        $(this).addClass("advSearchOpen").removeClass("advSearchClose");
        $('.advSearch').hide();
    })
    //}


    // Tooltip
    //============================
    $('a.linkTip').each(function() {
        $(this).tooltip({
            track: true,
            delay: 0,
            showURL: false,
            showBody: " - ",
            fade: 250
        });
    });


    // Podcast Walking Tours Flash
    //============================
    if ($(".walkingToursFlash").length > 0) {
        var city = $(".walkingToursFlash").attr("class").split(" ").splice(1, 1).toString();
        $('.walkingToursFlash').flash(
			{
			    src: '/content/podcasts/' + city + '.swf',
			    width: 535,
			    height: "100%",
			    wmode: "opaque",
			    scale: "showall",
			    wmode: "opaque",
			    devicefont: "false",
			    id: "podcastItem",
			    name: city,
			    menu: "true",
			    allowFullScreen: "true",
			    allowScriptAccess: "sameDomain",
			    movie: city,
			    id: "walkingTours_" + city
			},
			{ update: false,
			    version: '9.0.0'
			}
		);
    }




    // TEXAS RADIO FLASH
    //==========================
    $('#TexasRadioPlayer').each(function() {
        $('#TexasRadioPlayer').flash(
            {
                src: '/flash/gimp.swf',
                width: 188,
                height: 209,
                wmode: "transparent",
                scaleMode: "noScale",
                allowScriptAccess: "always",
                id: "texasRadioPlayer",
                flashvars: { a: trVars["artistID"], w: trVars["wsdl"], p: trVars["autoplay"], s: "true" }
            },
            { update: false, version: '9.0.0' });
        $("#TexasRadioPlayer").append("<div id='AmazonLinks' class='smallVideoPlayerExtras'/>");
    });

    // Texas Radio Remote Window
    //==================
    $(".openRadio").click(function(e) {
        e.preventDefault();
        openRemotePlayer();
    });


    // Trap Enter Key for Forms
    //=========================
    // class="trapEnter_buttonToTriggerID"
    $("*[class^='trapEnter']").bind('keydown keypress', function(e) {
        var code = e.charCode || e.keyCode;
        if (code == 13) {
            searchHasFocus = true;
            // Get applied class names and split to an array
            var classNames = $(this).attr("class").split(" ");
            // Sort through array to find trapEnter class
            for (var c = 0; c < classNames.length; c++) {
                if (classNames[c].indexOf("trapEnter") != -1) {
                    var but = classNames[c].substr(classNames[c].indexOf("_") + 1);
                }
            }
            $("#" + but).trigger("click");
        }
    });
	
	
	
	// Create an Account Jump link
	//============================
	$('#createAcctJump').each(function(){
		$(this).click(function(){
			location.href = '#createAcct';
			$('fieldset.createAcct .email').focus();
			return false;
		});
	});
	
	
	
	

});                //End jQuery function onload *************************
//*********************************************************

var searchHasFocus = false;
var tripPlannerOpen = 0;


// Launch/Close Trip Planner (launch used by TM's Trip Planner landing page flash)
//================================================================================
function launch_planner(){
	if(tpVars['userid']){ // user logged in
		$.openTripPlanner();
	} else { // user not logged in
		$("#signinBox").addClass("fixedPos");
		$("#openTripPlanner").attr("value",true);
		$.positionDiv("#signinBox");
		$("#signin").click();
	}
}
function close_planner() {
	$("#tripPlannerDiv").fadeOut("normal", function() {
		$("#tripPlannerDiv").remove();
		tripPlannerOpen = 0;
	});
	$(".coverup").fadeOut("normal", function() {
		$(".coverup").remove();
	});
	/*
	// Shrink Trip Planner on close
	$('#tripPlannerDiv').css({width:965, height:605});
	//$('#tripPlannerFlash').attr('width','100%').attr('height','100%');
	$('#tripPlannerFlash').remove();
	var tpImg = $('<img src="/images/tripPlanner_closingImage.jpg" border="0" />');
	tpImg.appendTo($('#tripPlannerDiv'));
	$('#tripPlannerDiv').css('backgroundColor','#6493BD').animate({left:tpSidebarLft, top:tpSidebarTop, width:205, height:129, opacity:0},850, function(){$("#tripPlannerDiv").remove();tripPlannerOpen=0;});
	$(".coverup").fadeOut("normal", function() {$(".coverup").remove();});
	*/
	RefreshSidebar();
}



// Show Sign In Over Trip Planner Flash
//=====================================
//$(function(){$('body').append('<div style="position:absolute;left:0;top:0;"><a href="#" onclick="showSignInFromTripPlanner()">Show Sign In</a></div>');});
var signInFromTripPlanner = 0;
function showSignInFromTripPlanner(action){
	// Remove from header
	$("#signinBox").addClass("fixedPos").css({zIndex:2000}).appendTo($('form'));
	$("#openTripPlanner").attr("value",true);
	if(action!=undefined || action!=null){
		$("#openTripPlannerAction").attr("value",action);
	}
	// Set variable to put back into header on close (handled in function above)
	signInFromTripPlanner = 1;
	$.positionDiv("#signinBox");
	$("#signin").click();
}






// Setup for Shrinking Trip Planner to TPSidebar
//==============================================
var tpSidebar, tpSidebarPos, scrollTop, tpSidebarTop, tpSidebarLft;
$(function(){
	/*if($('#tpSidebar').length>0){
		tpSidebar = $('#tpSidebar');
		tpSidebarPos = tpSidebar.offset();
		//scrollTop = $(window).scrollTop();
		tpSidebarTop = tpSidebarPos.top;// - scrollTop;
		tpSidebarLft = tpSidebarPos.left;
	}*/
});



// Newsletter Signup Analytics Tracking
//==============================================
/*
$(function(){
	$('#btnMailer, fieldset.createAcct .submitButton, fieldset.orderTG .submitButton').each(function(){
		$(this).click(function(){
			// Homepage
			if($('#emailNewsletter_email').length > 0){
				// Make sure it's a valid e-mail first
				var regExp = /^([A-Za-z0-9_\-\.+])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
				if(regExp.test($('#emailNewsletter_email').val())!=false){
					subscriberAnalytics('Homepage');
				}
			}
			// Create Account Forms
			if($('fieldset.createAcct input.newsletter:checked').length > 0){
				subscriberAnalytics('CreateAccount');
			}
			// Order Travel Guide Form
			if($('fieldset.orderTG input.newsletter:checked').length > 0){
				subscriberAnalytics('CreateAccount');
			}
		});
	});
});
function subscriberAnalytics(source){
	var visitor_country = '';
	if(google.loader.ClientLocation){
		visitor_country = google.loader.ClientLocation.address.country;
	}
	if(visitor_country == 'USA'){
		var country = visitor_country;
	} else if(visitor_country != 'USA' && visitor_country != ''){
		var country = 'International';
	} else {
		var country = 'Unknown';
	}
	pageTracker._trackEvent('NewsletterSignup', source, country);
}
*/





//********************************
// GLOBAL SCRIPTS
//********************************

// Destrop trip planner
//========================================
function KillTripPlanner() {
    $("#tripPlannerDiv").fadeOut("normal", function() {
        $("#tripPlannerDiv").remove();
        tripPlannerOpen = 0;
    });
    $(".coverup").fadeOut("normal", function() {
        $(".coverup").remove();
    });
}



// Position element centered on the screen
//========================================
$.positionDiv = function(id){
	var l = ($(window).width()-$(id).width())/2;
	var t = ($(window).height()-$(id).height())/2;
	$(id).css("left",l);
	$(id).css("top",t);	
	//If the User resizes the window, adjust the #container height
	$(window).bind("resize", function(){
		updatePosition(id)
	});
	
}
function updatePosition(id,w) {
	var l = ($(window).width()-$(id).width())/2;
	var t = ($(window).height()-$(id).height())/2;
	if(w!=1){
		$(id).css("left",l);
		$(id).css("top",t);	
	} else {
		$(id).css("left",l);
	}
}




// Search Region Dropdown cont.
//=============================
	// Change Region Map Image on MouseOver
	$.changeRegions = function(w){
		if(w!=0){$("p.map img").attr("src","images/region_map_"+w+".jpg");}
		else {$("p.map img").attr("src","images/region_map.jpg");}
	}
	// Highlight/UnHighlight ListItem That Matches Map
	$.highlightLI = function(w){
		$("#regionAlt ul li."+w).addClass("active");
	}
	$.unhighlightLI = function(w){
		$("#regionAlt ul li."+w).removeClass("active");
	}
	
	// Preload Images function
	$.preloadImages = function(){
		for(var i = 0; i<arguments.length; i++){
			$("<img>").attr("src", arguments[i]); 
		}
	}






// Cookie functions by http://www.quirksmode.org/js/cookies.html
//==============================================================
function createCookie(name,value,days){
	if (days){
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name){
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++){
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name){createCookie(name,"",-1);}
// /cookie functions



// POP-UP SURVEY CALL
//==============================================================
$(window).unload(function() {
    if(typeof window.checkCount == 'function') {
    checkCount();
    }
});


