$(function() {
    
    // sub-navigation accordion
    var subnavs = $(".level-2");
    if(subnavs.length > 0) {
        // get the current body id attribute
        var bodyID = $("body").attr("id");
        
        // set an active index to false (don't open anything)
        var activeIndex = false;
        
        subnavs.each(function(){
            // loop through each subnav
            var subnav = $(this);
            // get the li tags for each subnav, see if we have a match
            var liTags = subnav.find(" > li");
            liTags.each(function(index){
                if($(this).hasClass(bodyID)){
                    activeIndex = index;
                }
            });
            // create the accordion, referencing our activeIndex (int or false)
            subnav.accordion({
                header:'li span',
                active: activeIndex,
                collapsible: true,
                autoHeight: false,
                icons:{
                    header:"ui-icon-plus",
                    headerSelected:"ui-icon-minus"
                }
            });
        });
    }

    /* itinerary accordion */
    $(".itinerary").accordion({
        header:'h4',
        active: false,
        collapsible: true,
        autoHeight: false,
        icons:{
            header:"ui-icon-plus",
            headerSelected:"ui-icon-minus"
        }
    });
    
    /* general accordion */
    $(".accordion").accordion({
        header:'h4',
        active: false,
        collapsible: true,
        autoHeight: false,
        icons:{
            header:"ui-icon-plus",
            headerSelected:"ui-icon-minus"
        }
    });
    
    /*  lesson plans & videos accordion */
    $(".lesson-plans-accordion").accordion({
        header:'h3',
        active: false,
        collapsible: true,
        autoHeight: false,
        icons:{
            header:"ui-icon-plus",
            headerSelected:"ui-icon-minus"
        }
    });
    
    // var getPhotos = $("a.photo").attr['rel'] == 'shadowbox';
    $("a.photo").prepend("<span></span>");
    
    // add print button to destination comparison
    if($("body").hasClass("destination-comparison")) {
        if(window.print !== undefined) {
            var printBtn = $('<p id="print-btn">Print</p>');
            printBtn.bind("click", function(){
                window.print();
            });
            $("#center-column h1").after(printBtn);
        }
    }

    // add back button to interactive maps and destination comparison
    if($("body").hasClass("interactive-map") || $("body").hasClass("destination-comparison")) {
        if(history.length > 0) {
            var backBtn = $('<p id="back-btn">Back</p>');
            backBtn.bind("click", function(){
                history.go(-1);
            });
            $("#center-column h1").after(backBtn);
        }
    }

    /* destination comparison logic */
    if($("#destinations.destination-comparison").length > 0){
        // data containers
        var selectedDestinations;
        
        // element references
        var container = $(".destination-comparison-container").eq(0);
        var checkboxes = $("#destinations-list input:checkbox");
        
        // stripe table rows
        container.find('table tr:even').addClass('alt');
        
        // close (x) icons on table headers - remove this destination from table
        container.find(".close-btn").each(function(index){
            $(this).bind("click", function(){
                var checkbox = $("#destinations-list input:checkbox[value="+(index+1)+"]");
                checkbox.removeAttr("checked");
                checkbox.trigger("change");
            });
        });
        
        // hide the container initially
        container.hide();
        
        // what to do when a checkbox is clicked - only allow 5 destinations
        checkboxes.bind("click change", function(){
            selectedDestinations = checkboxes.filter(":checked");
            var unchecked = checkboxes.not(":checked");
            if(selectedDestinations.length == 5){
                unchecked.attr("disabled", "disabled");
                unchecked.parent("label").addClass("disabled");
            } else {
                checkboxes.removeAttr("disabled");
                unchecked.parent("label").removeClass("disabled");
            }
            updateComparisonTable(container, selectedDestinations);
        });
    }
    
    // twitter status widget (hide until success)
    $("#twitter-feed").hide();
    var twitterURL = "http://api.twitter.com/1/statuses/user_timeline.json?screen_name=discoverytrips&count=3";
    $.ajax({
        url: twitterURL,
        dataType: "jsonp",
        success: function(data, status, xhr){
            $("#twitter-feed").show();
			
			var currTweets = '';
			var urlRegEx;
			var fullURL = '';
			var displayedURL = '';
			var linkifiedURL = '';
			var startIndex;
						
            //$("#twitter_update_list").html("<li>" + data[0].text + "</li><br><li>" + data[1].text + "</li><br><li>" + data[2].text + "</li>");
			for(var i = 0; i <3; i++){
				var myTweetString = '';								
				var myTweet = data[i].text;
				
				urlRegEx = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/im;
				fullURL = urlRegEx.exec(myTweet);
				startIndex = 0;
						
				while (fullURL != null)
				{					
					displayedURL = fullURL[0];
						
					if (fullURL[0].length > 25)
					{							
						displayedURL = fullURL[0].substring(0,25) + '...';							
					}
					linkifiedURL = "<a href='" + fullURL[0] + "' title='" + fullURL[0] + "' target='_blank'>" + displayedURL + "</a>";
					myTweet = myTweet.replace(fullURL[0], linkifiedURL);
					startIndex = myTweet.lastIndexOf(linkifiedURL) + linkifiedURL.length;
					fullURL = urlRegEx.exec(myTweet.substring(startIndex));
				}
				
				myTweetString = myTweet;				  				  
				currTweets = currTweets + "<br><li>" + myTweetString + "</li>";
        	}			
			$("#twitter_update_list").html(currTweets);
        }
    });
	
	// twitter HASH status widget (hide until success)
    $("#twitter-feed-hash").hide();
	var hashTag = $("#hiddenHash").val();
    var twitterURL = "http://search.twitter.com/search.json?q=%23" + hashTag + "&from%3A100272344&result_type=recent";
    $.ajax({
        url: twitterURL,
        dataType: "jsonp",
        success: function(data, status, xhr){
            $("#twitter-feed-hash").show();
			
			var currTweets = '';
			var urlRegEx;
			var fullURL = '';
			var displayedURL = '';
			var linkifiedURL = '';
			var startIndex;
			var tweetCount = data.results.length;
			
			if (tweetCount > 3)
			{
				tweetCount = 3;
			}
						
            for(var i = 0; i < tweetCount; i++){
				var myTweetString = '';								
				var myTweet = data.results[i].text;
				
				urlRegEx = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/im;
				fullURL = urlRegEx.exec(myTweet);
				startIndex = 0;
						
				while (fullURL != null)
				{					
					displayedURL = fullURL[0];
						
					if (fullURL[0].length > 25)
					{							
						displayedURL = fullURL[0].substring(0,25) + '...';							
					}
					linkifiedURL = "<a href='" + fullURL[0] + "' title='" + fullURL[0] + "' target='_blank'>" + displayedURL + "</a>";
					myTweet = myTweet.replace(fullURL[0], linkifiedURL);
					startIndex = myTweet.lastIndexOf(linkifiedURL) + linkifiedURL.length;
					fullURL = urlRegEx.exec(myTweet.substring(startIndex));
				}
				
				myTweetString = myTweet;				  				  
				currTweets = currTweets + "<br><li>" + myTweetString + "</li>";
        	}			
			$("#twitter_hash_list").html(currTweets);
        }
    });

    // home page swf
    var videoPlayer = $("#home #video-player");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/player-home.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "video-player", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-home.swf", "video-player", "580", "440", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    // destination page swfs
    var videoPlayer = $("#destinations #video-trips");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/destination-overview.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "video-trips", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "video-trips", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    var videoPlayer = $("#arctic #video-trips");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/destination-arctic.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "video-trips", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "video-trips", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    var videoPlayer = $("#arizona-grand-canyon #video-trips");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/destination-arizona-grand-canyon.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "video-trips", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "video-trips", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    var videoPlayer = $("#australia #video-trips");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/destination-australia.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "video-trips", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "video-trips", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    var videoPlayer = $("#china #video-trips");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/destination-china.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "video-trips", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "video-trips", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    var videoPlayer = $("#costa-rica #video-trips");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/destination-costa-rica.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "video-trips", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "video-trips", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    var videoPlayer = $("#ecuador-galapagos #video-trips");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/destination-ecuador-galapagos.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "video-trips", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "video-trips", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    var videoPlayer = $("#france-germany #video-trips");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/destination-france-germany.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "video-trips", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "video-trips", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    var videoPlayer = $("#italy-greece #video-trips");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/destination-italy-greece.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "video-trips", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "video-trips", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    var videoPlayer = $("#london-paris #video-trips");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/destination-london-paris.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "video-trips", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "video-trips", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    var videoPlayer = $("#new-zealand-australia #video-trips");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/destination-new-zealand-australia.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "video-trips", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "video-trips", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    var videoPlayer = $("#scotland-london-paris #video-trips");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/destination-scotland-london-paris.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "video-trips", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "video-trips", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    var videoPlayer = $("#south-africa #video-trips");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/destination-south-africa.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "video-trips", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "video-trips", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    var videoPlayer = $("#spain-portugal #video-trips");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/destination-spain-portugal.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "video-trips", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "video-trips", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    var videoPlayer = $("#washington-dc #video-trips");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/destination-washington-dc.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "video-trips", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "video-trips", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    // about us swfs
    var videoPlayer = $("#about-us.hear-from-our-travelers #videoplayer");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/about-hear-travelers.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "videoplayer", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "videoplayer", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    var videoPlayer = $("#about-us.make-a-difference #videoplayer");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/about-make-difference.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "videoplayer", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "videoplayer", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    // students swfs
    var videoPlayer = $("#students #videoplayer");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/student-overview.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "videoplayer", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "videoplayer", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    // parents swfs
    var videoPlayer = $("#parents #videoplayer");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/parent-overview.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "videoplayer", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "videoplayer", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
    
    // teacher page swfs
    var videoPlayer = $("#teachers #videoplayer");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/teacher-overview.xml" };
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "videoplayer", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "videoplayer", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }

    var videoPlayer = $("#teachers.getting-started #videoplayer");
    if(videoPlayer.length > 0){
        var flashvars = { xmlPath: "/media/xml/teacher-getting-started.xml" }; 
        var params = { wmode: "transparent", allowFullScreen: "true" };
        var attributes = { id: "videoplayer", name: "flash-player" };
        swfobject.embedSWF("/media/swf/player-trips.swf", "videoplayer", "460", "365", "9.0.0", "/media/swf/expressInstall.swf", flashvars, params, attributes);
    }
});

function updateComparisonTable(container, selectedDestinations){
    // data containers
    var selectedIndicies = [];
    
    // get the table rows
    var tableRows = $("#destination-table tr");
    
    // get the value of each checkbox (which is an integer)
    selectedDestinations.each(function(){
        selectedIndicies.push($(this).val());
    });
    
    // get the width of the entire table and the first column
    var tableWidth = container.width();
    var firstColumnWidth = container.find("tr:first th:first").width();
    var dataWidth = tableWidth - firstColumnWidth;
    
    if(selectedDestinations.length > 1){
        // 2 or more destinations were checked, show the container
        container.show();
        
        // calculate the width each column should be
        var colWidth = dataWidth / selectedDestinations.length;
        
        // determine which is the last column so we can add a "last" class to it
        var lastIndex = selectedIndicies[selectedIndicies.length - 1];
        
        // loop through each row and hide the column if necessary
        tableRows.each(function(){
            var columns = $(this).children();
            columns.each(function(index, col){
                var column = $(col);
                column.removeClass("last");
                if(index != 0){
                    if($.inArray(index.toString(), selectedIndicies) != -1){
                        if(index == lastIndex) column.addClass("last");
                        column.css("width", colWidth);
                        column.show();
                    } else {
                        column.hide();
                    }
                }
            });
        });
    } else {
        // less than 2 destinations were checked, hide the container
        container.hide();
    }
}