$(document).ready(function() {


	
	
	/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
	
	   FOR TESTING ONLY. DO NOT POST TO LIVE SERVER

       !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */
       
       /*
	if(location.href.indexOf("beta.traveltex.com")!=-1 || location.href.indexOf(".36")!=-1){
		$("img").each(function(){
			if($(this).attr("alt")==""){
				$(this).css("border","5px solid red");
			}
		});
		var testLabels = $("label");
		$("input, select, textarea").each(function(){
			var eID = $(this).attr("id");
			var testMatch = 0;
			for(var t=0; t<testLabels.length; t++){
				if($(testLabels[t]).attr("for")==eID){
					testMatch = 1;
				}
			}
			if(testMatch==0){
				$(this).css("border","5px solid red");
				if($(this).attr("type") == "checkbox" || $(this).attr("type") == "radio"){
					$(this).css("width","4em").css("height","4em");
				}
			}
		});
	}
	*/
	/* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
    //******************************************
    // HOME PAGE SCRIPTS
    //******************************************

    // 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
    //====================
    $('#home_accord_flash_alt').flash(
        {
            src: 'flash/accordion.swf',
            width: 338,
            height: 375,
            wmode: "opaque",
            id: "home_accordion"
        },
        { update: false,
            version: '9.0.0'
        }
    );









    //******************************************
    // 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();
            });
        }
        window.open($(this).attr("href"));
    });
    // Trigger handler for all offsite links with target=_blank
    $("a[target='_blank'][rel!='pdf']:not([href^='/']):not([rel*='notOffsite'])").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") {
                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"]').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["#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"] = "Activities, Attractions or Events";
    inputs["#activitySearchTxt"] = "Search for Activities & 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 ($.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");
        } else {
            $("#signinBox").fadeOut("fast");
        }

    });





    // 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 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").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 });
    }





    // 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 li a").click(function(e) {
        e.preventDefault();
        $(this).parent().find("ul").fadeIn()
    });



    // Lodging Sidebar Search
    if ($("p.lodgingSidebarButton a").length > 0) {
        $("p.lodgingSidebarButton a").click(function(e) {
            e.preventDefault();
            var cloneID = 88;
            var groupID = $(".lodgingCitySearch #city").val();
            var lodgingID = $(".lodgingCitySearch #type").val();
            var startDate = $(".lodgingDatesSearch #checkIn").val();
            var endDate = $(".lodgingDatesSearch #checkOut").val();
            if (groupID == "" || lodgingID == "" || startDate == "" || endDate == "") {
                $(".lodgingError").html("<p>Please provide information for all fields.</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: true, width: 560, minChars: 2, extraParams: { t: "City"} });
    //	$("#activitySearchTxt").autocomplete("http://new.traveltex.com/sayt.aspx", { autoFill: true, width: 560, minChars: 2, extraParams: { t: "Activity|Type:Golf Course|Type:Campground|Type:Ranch|Type:Rodeo"} });
    //	$("#eventSearchTxt").autocomplete("http://new.traveltex.com/sayt.aspx", { autoFill: true, width: 560, minChars: 2, extraParams: { t: "Event"} });
    //	$("#ttdSearchTxt").autocomplete("http://new.traveltex.com/sayt.aspx", { autoFill: true, width: 560, minChars: 2, extraParams: { t: "Activity|Type:Event|Type:Golf Course|Type:Campground|Type:Ranch|Type:Rodeo"} });
    $(".weatherSearchTxt").autocomplete("/sayt.aspx", { autoFill: true, width: 560, minChars: 2, extraParams: { t: "City"} });

    $(".advSearchCityField").autocomplete("/sayt.aspx", { autoFill: true, width: 287, minChars: 2, extraParams: { t: "City"} });
    //	$(".advSearchKeywordField").autocomplete("http://new.traveltex.com/sayt.aspx", { autoFill: true, width: 287, minChars: 2 });


    // Show Advanced Search Options
    //=============================
    $(".advSearch .category").change(function() {
        $(".advSearchOptions").hide(); // hide all of them first
        $(".listitem :checkbox").attr("checked", false); // Clear the checkboxes
        $(".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).fadeIn();
        }
    });
    // If the dropdown is preselected on page load
    if ($(".advSearch .category :selected").text() != "") {
        var selected = $(".advSearch .category :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).show();
        }
    }

    // Show Sub Category Search Options
    //=================================
    $(".listitem :checkbox").each(function() {
        $(this).click(function() {
            // If they are checking it...
            if ($(this).attr("checked") == true) {
                // See if the category has a subcategory
                if ($(this).nextAll("div").length > 0) {
                    // Make sure the next div is actually a subcategory
                    if ($(this).nextAll("div").get(0).className == "subcats") {
                        $(this).nextAll("div").fadeIn();
                    }
                }
            }
            // If they are unchecking it...
            else {
                if ($(this).nextAll("div").length > 0) {
                    if ($(this).nextAll("div").get(0).className == "subcats") {
                        $(this).nextAll("div").hide();
                        // Uncheck all sub categories
                        for (var s = 1; s <= $(this).siblings("div").find("input").length; s++) {
                            $(this).siblings("div").find("input").attr("checked", false);
                        }

                    }
                }
            }
        });
        // On page load, check for checked boxes
        if ($(this).attr("checked") == true) {
            // See if the category has a subcategory
            if ($(this).nextAll("div").length > 0) {
                // Make sure the next div is actually a subcategory
                if ($(this).nextAll("div").get(0).className == "subcats") {
                    $(this).nextAll("div").fadeIn();
                }
            }
        }
    });

    // Datepicker for Events 
    //======================
    if ($(".begDate").length > 0) { $(".begDate").datepick({ showOn: 'both', buttonImageOnly: true, buttonImage: 'images/cal_icon.gif' }); }
    if ($(".endDate").length > 0) { $(".endDate").datepick({ showOn: 'both', buttonImageOnly: true, buttonImage: 'images/cal_icon.gif' }); }
    if ($(".eventDate").length > 0) { $(".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())
        });
    });
    // 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
    //******************************************



    // 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");
            //Embed Flash into DIV
            $('#tripPlannerDiv').flash(
				{
				    src: 'flash/tripPlannerShell.swf',
				    width: 965,
				    height: 605,
				    id: "tripPlannerFlash",
				    wmode: "window",
				    flashvars: { u: tpVars["userid"], t: (tripID != null ? tripID : tpVars["tripid"]), w: tpVars["wsdl"], k: tpVars["gkey"], n: tpVars["name"] }
				},
				{ 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");
        }
    });

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

var searchHasFocus = false;
var tripPlannerOpen = 0;


function launch_planner(){
	$.openTripPlanner();
}
function close_planner() {
	$("#tripPlannerDiv").fadeOut("normal", function() {
		$("#tripPlannerDiv").remove();
		tripPlannerOpen = 0;
	});
	$(".coverup").fadeOut("normal", function() {
		$(".coverup").remove();
	});
	RefreshSidebar();
}









//********************************
// 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() {
    checkCount();
});

