/* PAGE VARIABLES */
var wl_add_error = 'There was an error saving your wish list selection. The server might be busy or your connection may have been lost. Please try again later.';
var wl_delete_error = 'There was an error removing your wish list selection. The server might be busy or your connection may have been lost. Please try again later.';

var compareURI = '/trips/compare';

var currRollOver = '';
var restoreMenuTimer = 0;
var hideSlideInfoTimer = null;
var tabCookieName = '';

jQuery(function() {
    // init Page Elements and Page specfic vars and functions
    //jQuery('#box-space>div:first').addClass('first');
    // TRIP LIST SPECIFIC INIT
    if (elementExists('#trip-list')) {
        tab_cookie_name = "active_navigator_tab";
        jQuery(window).bind("resize",
        function() {
            setListSize();
        });
        // delaying for Safari bug but seems to help everyone
        var listSizeTimer = setTimeout("setListSize()", 10);
    }
    // ITINERARY SPECIFIC INIT
    if (elementExists('#itinerary-page')) {
        tab_cookie_name = "active_itinerary_tab";

        // jQuery('#image-set').cycle('pause');

        // jQuery('#overview,#glance,#accommodations,#leaders,#comments,#slideshow,#overview_test,#glance_test,#accommodations_test,#leaders,#comments,#slideshow').click(function() {
        //    jQuery('#image-set').cycle('pause');
        //});

    }
    initTabs();
    
    mainmenu();
    
    jsSearch();
    
    // init Add to Wish List links
    initAddToWLinks();
    // image info rollover
    if (elementExists('.info-bug')) initImageInfo();

    initSlideshow();
    
    // set the country menu
    jQuery('#country').clone().attr('id', 'all-countries').appendTo(jQuery('body'));
    
  // if there's a region selected, limit the country list
  currSelectedRegion = jQuery('#region option:selected').attr('value');
  if (currSelectedRegion != 'any-region') {
    changeRegion(currSelectedRegion);
  }
    
	if ( jQuery.browser.msie  && jQuery.browser.version < 7 ) {
	    var timeDelay = setTimeout(function() {
	        var sideBarHeight = jQuery("#sidebar").height();
			var tabPage = (jQuery(".tabs").length > 0);
			var content = jQuery(".content");
	        if (jQuery("#main").height() < sideBarHeight) {
				if (tabPage) content.hide();
	            jQuery("#main").height(sideBarHeight);
				if (tabPage) content.show();
	        }
	    },
	    500);
	}	
});

function jsSearch(){
  jQuery("#view-results-button").html('<a href="javascript:searchUrl();"><img src="/images/tf-widget/btn-view-results.gif" alt="View Results" style="padding: 2px;" /></a>');
}

function itinActionList(){
  jQuery.ajax({
    url: '/admin/itineraries/actions',
    timeout: 2000,
    dataType: 'html',
    error: function() {
      alert("Error");
    },
    success: function(data, textStatus) {
      jQuery('#itin-report').html(data);
      jQuery('#itin-report').addClass('report');
    },
    complete: function() {
    }
  });
}

function searchUrl(){
  var goToUrl = "/trips" + getSelection("region") + getSelection("country") + getSelection("activity") + getSelection("date") + getSelection("difficulty")
  window.location = goToUrl;
}

function getSelection(key){
  var currValue = jQuery("#" + key + " option:selected").attr('value');
  if (currValue != 'any-' + key) {
    return "/" + currValue
  }
  return ""
}

function mainmenu(){
jQuery(" #nav-bar li").hover(function(){
    jQuery(this).find('ul:first').css({visibility: "visible",display: "none"}).show(0);
  },
  function(){
    jQuery(this).find('ul:first').css({visibility: "hidden"});
  });
}

/* SEARCH FIELD */

function searchField(TorF) {
    var currValue = jQuery('#search_phrase').val();
    if (TorF) {
        if (currValue == "search") jQuery('#search_phrase').val('');
    } else {
        if (currValue == "") jQuery('#search_phrase').val('search');
    }
}

/* Slideshow Initialization */

function initSlideshow() {
    // slideshow
    if (elementExists('#image-set'))
      jQuery('#image-set').cycle({
        fx: 'fade',
        timeout: 8000,
        delay: 300,
        speed: 2000,
        nowrap: true,
        prev: '#slide-prev',
        next: '#slide-next',
        before: switchText
     });
}

function initImageInfo() {
    var IEPre7 = (jQuery.browser.msie && jQuery.browser.version < 7);
    if (IEPre7) {
        //swap out alpha transparent images with index transparency for IE
        // force the load of the images
        jQuery(document.createElement('img')).src = '/images/slide-show/info-btm-mask-ie.gif';
        jQuery(document.createElement('img')).src = '/images/slide-show/info-top-mask-ie.gif';
        jQuery(document.createElement('img')).src = '/images/slide-show/info-bug-ie.gif';
        jQuery(document.createElement('img')).src = '/images/slide-show/info-bug-on-ie.gif';

        jQuery('.info-bug').attr('src', '/images/slide-show/info-bug-ie.gif').css({
            height: 26,
            width: 38,
            opacity: 0.8
        });
        jQuery('#slide-info, #image-info').css('background-image', 'url(/images/slide-show/info-btm-mask-ie.gif)');
        jQuery('.info-inner').css('background-image', 'url(/images/slide-show/info-top-mask-ie.gif)');
    } else {
        // if it's not IE6 make slide-info semi-transparent
        jQuery('#home-page #slide-info, #image-info').css('opacity', 0.8);
        jQuery(document.createElement('img')).src = '/images/slide-show/info-btm-mask.png';
        jQuery(document.createElement('img')).src = '/images/slide-show/info-top-mask.png';
        jQuery(document.createElement('img')).src = '/images/slide-show/info-bug.png';
        jQuery(document.createElement('img')).src = '/images/slide-show/info-bug-on.png';
    }

    // image information pop-ups	
    jQuery('.info-bug').hover(function() {
        if (hideSlideInfoTimer) clearTimeout(hideSlideInfoTimer);
        if (elementExists('#image-set')) jQuery('#image-set').cycle('pause');
        if (IEPre7) {
            jQuery(this).attr('src', '/images/slide-show/info-bug-on-ie.gif');
        } else {
            jQuery(this).attr('src', '/images/slide-show/info-bug-on.png');
        }
        jQuery(this).siblings(".slide-info").show();
    },
    function() {
        delayInfoHide(this);
    });

    // show the info rollover button
    jQuery('.info-bug').show();
}

function wishListItemsExist() {
    return (jQuery('#wl-list div').length != 0);
}

// INIT ADD TO WISH LIST LINKS
function initAddToWLinks() {
    jQuery('a.wl-add').click(function() {
        var rowID = 'wl-' + this.name;
        if (this.className == 'wl-add-dim' || jQuery('#wl-list #' + rowID).length) {
            return false;
        }
        manageAddLinks(this.name, 'dim');
        jQuery(this).css('background-image', 'url(/images/spinner.gif)');
        addToWishList(this.name, this.rel, this);
    });
}

/* SLIDESHOW AND IMAGE CODE */

function delayInfoHide(infoBugObj) {
    whichToHide = infoBugObj;
    hideSlideInfoTimer = setTimeout('hideSlideInfo()', 300);
}

function hideSlideInfo() {
    if (whichToHide) {
        if ((jQuery.browser.msie) && (jQuery.browser.version < 7)) {
            jQuery(whichToHide).attr('src', '/images/slide-show/info-bug-ie.gif');
        } else {
            jQuery(whichToHide).attr('src', '/images/slide-show/info-bug.png');
        }
        jQuery(whichToHide).siblings(".slide-info").hide();
        if (elementExists('#image-set')) jQuery('#image-set').cycle('resume');
    }
}

function switchText() {
    jQuery('#slide-info > .info-inner').html(jQuery(this).children('div').html());
}

/* TAB PAGE FUNCTIONS */

var curr_tab = '';

function initTabs() {
    if (elementExists('.tabs')) {
        jQuery('.tabs li:first').addClass('first');
        jQuery('.tabs li:last').addClass('last');
        // delaying for a Safari bug but it seems to help everyone
        var tabInitTimer = setTimeout("displayTabs()", 10);
        jQuery('.tabs li').click(function() {
            switchSection(this.id);
        }).hover(function() {
            hilightTab(this.id, true);
        },
        function() {
            hilightTab(this.id, false);
        });
    }
}

function switchSection(key) {
  displaySection(key);
  var stateObj = { foo: "bar" };
  jQuery.get('/tab/' + key);
}

function displayTabs() {
    var active_tab = jQuery.cookie(tab_cookie_name);
    active_tab = (tabTest(active_tab)) ? active_tab: jQuery('div.tabs li:first').attr('id');
    curr_tab = jQuery('div.tabs li:first').attr('id');
    displaySection(active_tab);

    jQuery('.tabs').css('visibility', 'visible');
}

function tabTest(tab_id) {
    if ((tab_id === null || tab_id === "")||(!elementExists('#' + tab_id + '_content'))) {
        return false;
    }
    return true;
}

function hilightTab(key, TorF) {
    if (curr_tab != key) {
        if (TorF) jQuery('#' + key).addClass('rollover');
        else jQuery('#' + key).removeClass('rollover');
    }
}

function displaySection(key) {
    if (curr_tab) hideSection(curr_tab);
    showSection(key);
    curr_tab = key;
    jQuery.cookie(tab_cookie_name, key);
}

function showSection(key) {
    jQuery('#' + key).removeClass('rollover').addClass('current');
    jQuery('#' + key).next().addClass('nextTab');
    jQuery('#' + key + '_content').attr('className', 'now_showing');
}

function hideSection(key) {
    jQuery('#' + key).removeClass('current');
    jQuery('#' + key).next().removeClass('nextTab');
    jQuery('#' + key + '_content').attr('className', 'in_the_wings');
}

function setListSize() {
    // going to have to do something for IE but I don't know what it is yet.
    // 264 = height of the header + height of the footer + a lititle margin
    // 300 = height of the TF widget + the height of one ad
    // these numbers are a little strange? still need to do some figuring
    var minListHeight = (jQuery('#sidebar').height());
    var browserHeight = jQuery(window).height();
    var innerSpace = Math.max((browserHeight - 600), minListHeight);
    /* height of browser with scrollbar */
    /* jQuery('#trip-list').height(innerSpace); */
}

/* WISH LIST & LAST VIEWED SHARED CODE */

function scrollBottom(whichElement) {
    var bScroll = document.getElementById(whichElement);
    bScroll.scrollTop = bScroll.scrollHeight;
}

/* WISH LIST CODE */

var addToWishList = function(itinCode, itinName, spinnerObj) {
    var rowID = 'wl-' + itinCode;
    var newRow = jQuery('<div class="list-item"></div>').appendTo('#wl-list');
    jQuery(newRow).attr('id', rowID)
    .css('display', 'none')
    .html('<p>' + itinName + '</p>');
    jQuery(newRow).addClass('temp').show();
    scrollBottom('wl-list');
    // scroll list to bottom to display new item
    sendWishListAddToServer(itinCode, newRow, spinnerObj);
}

function manageAddLinks(itinCode, direction) {
    setAddLinks(jQuery("a[name='" + itinCode + "']"), direction);
}

function setAddLinks(collection, direction) {
    jQuery(collection).each(function() {
        if (direction == 'restore') {
            jQuery(this).attr('class', 'wl-add');
            // dim add link anywhere on the page
        } else {
            jQuery(this).attr('class', 'wl-add-dim');
            // dim add link anywhere on the page
        }
    });
}

function sendWishListAddToServer(itinCode, newRow, spinnerObj) {
    jQuery.ajax({
        url: '/wishlists/create/' + itinCode,
        timeout: 2000,
        dataType: 'html',
        error: function() {
            alert(wl_add_error);
            removeFromWLComplete(itinCode);
            manageAddLinks(itinCode, 'restore');
            // dim add links in main body
        },
        success: function(data, textStatus) {
            //jQuery('#wl-body').remove()
            jQuery('#wl-body').replaceWith(data);
            // data is the new HTML for the row
            counter = jQuery(".list-item", "#wl-list").length
            jQuery('#wl-counter').html("(" + counter + " items)");
            manageAddLinks(itinCode, 'dim');
            // dim add links in main body
            scrollBottom('wl-list');
            // scroll list to bottom to display new item
        },
        complete: function() {
            // don't need this since we will get the whole list back from the server
            if (spinnerObj) jQuery(spinnerObj).removeAttr('style');
        }
    });
}

function removeFromWL(itinCode) {
    jQuery.ajax({
        url: '/wishlists/destroy/' + itinCode,
        timeout: 2000,
        dataType: 'html',
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(errorThrown);
        },
        success: function(data) {
            removeFromWLComplete(data, itinCode);
        }
    });
}

function removeFromWLComplete(data, itinCode) {
    //jQuery('#wl-body').remove()
    jQuery('#wl-body').replaceWith(data);
    counter = jQuery(".list-item", "#wl-list").length
    jQuery('#wl-counter').html("(" + counter + " items)");

    jQuery('#wl-list div:first').addClass('first');
    manageAddLinks(itinCode, 'restore');
    // undim add button in TF list
}

/* TRIP FINDER CODE */

function changeRegion(region) {
    if (jQuery.browser.msie && jQuery.browser.version < 7)
    jQuery("#country").css({
        visibility: "hidden"
    });
    // fix for bad IE6 behavior
    // get the class of the currently selected country
    var currCountryClass = jQuery("#country option:selected").attr('className');
    // get the value of the currently selected country
    var currCountryValue = jQuery("#country option:selected").attr('value');
    if (region == 'any-region') {
        jQuery("#country").empty().append(jQuery('#all-countries option').clone());
        setCountry(currCountryValue);
    } else {
        // get the region code from the class of the region option
        var regionCode = jQuery("#region option:selected").val();
        // create a clone of just the option elements that contain the region class code
        var newSet = jQuery("#all-countries option." + regionCode).clone();
        // replace the current set of countries with a new set of countries
        jQuery("#country").empty().append(newSet);
        // if the currently selected country does not contain the current region code
        // then switch to any-country or the first country if there is only one country in that region
        if (jQuery("#country option").length == 2) {
            setCountry(regionCode);
        } else if (currCountryClass.indexOf(regionCode) != -1) {
            // restore the old selection
            setCountry(currCountryValue);
        }
    }
    if (jQuery.browser.msie && jQuery.browser.version < 7)
    jQuery("#country").css({
        visibility: "visible"
    });
    // fix for bad IE6 behavior
}

function setCountry(country) {
    jQuery("#country option[value='" + country + "']").attr('selected', 'selected');
}

/* Clear Trip Finder selections */

function clearFinder() {
    if (jQuery.browser.msie && jQuery.browser.version < 7)
    jQuery("#country").css({
        visibility: "hidden"
    });

    jQuery("#country").empty().append(jQuery('#all-countries option').clone());

    jQuery("#region option[value='any-region']").attr('selected', 'selected');
    jQuery("#country option[value='any-country']").attr('selected', 'selected');
    jQuery("#activity option[value='any-activity']").attr('selected', 'selected');
    jQuery("#date option[value='any-date']").attr('selected', 'selected');
    jQuery("#difficulty option[value='any-difficulty']").attr('selected', 'selected');

    if (jQuery.browser.msie && jQuery.browser.version < 7)
    jQuery("#country").css({
        visibility: "visible"
    });
}

function printItinerary(key) {
  window:print();
  jQuery.get('/itineraries/print/' + key);
}

function explainLevel() {
    jQuery.facebox({ ajax: '/itineraries/level' });
}

function explainPricing(itin) {
    jQuery.facebox({ ajax: '/itineraries/' + itin + '/pricing' });
}

function routeMap(map) {
    jQuery.facebox({ image: map });
}

function stops(day) {
  jQuery.facebox({ ajax: '/accommodations/day-thumb/' + day })
}

function lodging(accomm) {
  jQuery.facebox({ ajax: '/accommodations/popup/' + accomm })
}

/* POP-UP CODE */

function displayPopup(key, URI, title) {
    //if (elementExists('#image-set')) jQuery('#image-set').cycle('pause');
    var popUpKey = 'pop-' + key;
    // if the requested pop-up doesn't already exist create it
    if (!jQuery('#' + popUpKey).length) {
        // build the base pop up object, and get the object
        var popUpObj = jQuery('<div class="pop-up-wrapper"><div class="pop-up-mask">&nbsp;</div><div class="pop-up"><div class="pop-up-bar"><a href="javascript:closePopup(\'' + popUpKey + '\');" class="close">close</a><h1></h1></div><div class="pop-up-content"><div class="content"></div></div></div>').appendTo(jQuery(document.body));
        popUpObj.attr('id', popUpKey);
        popUpObj.children('.pop-up-mask').css('opacity', 0.6);
        jQuery('<img />').attr({
            src: '/images/pop-ups/label-' + key + '.gif',
            alt: title
        }).appendTo(jQuery('#' + popUpKey + ' h1').eq('0'));
        jQuery.get(URI,
        function(data) {
            jQuery('#' + popUpKey + " .content").append(data);
        });
    } else {
        var popUpObj = jQuery('#' + popUpKey);
    }
    jQuery(popUpObj).show();
    setShadow('#' + popUpKey + " .pop-up");
}

var setShadow = function(key) {
    if (jQuery(key).height() < 100) {
        var shadowTimer = setTimeout("setShadow('" + key + "')", 100);
    } else {
        jQuery(key).dropShadow({
            opacity: .4
        });
        setShadow = function(key) {
            jQuery(key).redrawShadow();
        }
    }
};

// closes the last dialog so that it's multidialog safe.
function closePopup(popID) {
    // hide, don't remove so if they call it again it loads faster
    jQuery('#' + popID).remove();
    // if the slideshow is paused resume it
    //if (elementExists('#image-set')) jQuery('#image-set').cycle('resume');
}

/* COMPARE TRIPS */

function compareTrips() {
    if (wishListItemsExist()) displayPopup('compare', compareURI, 'Compare Wish List Itineraries');
    // self initializing pop-up
}

function compareTheseTrips(trips) {
    displayPopup('compare', compareURI + "/" + trips, 'Compare Itineraries');
    // self initializing pop-up
}

var compare = function() {
    var displayAll = true;
    // Private functions for changeColumn
    // fix the header widths to match the table columns
    var fixHeaderWidths = function() {
        jQuery('#top-scroller div').each(function(index) {
            jQuery(this).width(jQuery('#comp-scroller table tr td').eq(index).width());
        });
    };

    // remove the instructions if there are elements
    // restrict the size of the header divs if there are more than three, fixes some ugly line breaks
    var adjustUI = function() {
        (displayArray.length > 2) ? jQuery('#top-scroller').addClass('limit') : jQuery('#top-scroller').removeClass('limit');
        jQuery('#pop-compare #viewer').css('display', (displayArray.length) ? 'block': 'none');
    };

    // move the scroll if the new element is not visible
    var adjustScroll = function(arrayPos) {
        var scroller = document.getElementById('comp-scroller');
        if (arrayPos == 1) {
            // if it's first just go first
            scroller.scrollLeft = 0;
        } else if (arrayPos == displayArray.length) {
            // if it's last then go last
            scroller.scrollLeft = jQuery('#comp-scroller table').width();
        } else {
            // otherwise work it out
            var start = scroller.scrollLeft;
            var posStart = ((arrayPos - 1) * 160);
            if (posStart < start) {
                // check the beginning of the new element
                scroller.scrollLeft = posStart;
                // adjust
            } else if ((posStart + 160) > (start + jQuery('#comp-scroller').width())) {
                // check the end
                scroller.scrollLeft = posStart;
                // adjust
            }
        }
        scroller.scrollTop = 0;
        jQuery('#top-scroller').css('left', -document.getElementById('comp-scroller').scrollLeft + 'px');
    };

    var addColumn = function(key, cleanUp) {
        var newLength = displayArray.push(key);
        displayArray.sort();
        var index = jQuery.inArray(key, displayArray);
        var colIndex = (index + 1);
        // get the position of the element
        var insert = (colIndex == newLength) ? 'after': 'before';
        var cellData = tripData[ + key];
        // get just the cells we're working with
        var itinCode = cellData[0];
        // title
        var title = jQuery('<div>').html(cellData[1]);
        if (insert == 'after' || jQuery('#viewer #top-scroller div').length === 0) {
            jQuery('#viewer #top-scroller').append(title);
        } else {
            jQuery('#viewer #top-scroller div').eq(colIndex - 1).before(title);
        }
        // download
        // details
        loadCell(1, colIndex, cellData[8], insert);
        loadCell(2, colIndex, '<a href="' + cellData[13] + '/download"><img src="/images/pop-ups/btn-download-full.gif" alt="Download Trip Brochure" /></a><br/><img src="/images/x.gif" height="1" width="160" alt="" />', insert, 'center');
        // reserve
        // loadCell(3,colIndex,'<a href="'+cellData[13]+'/reservation");"><img src="/images/pop-ups/btn-reserve-this-trip.gif" alt="Reserve this Trip" /></a><br/><img src="/images/x.gif" height="1" width="160" alt="" />',insert,'center');			
        // length
        loadCell(4, colIndex, '<h3>Activity</h3>' + cellData[2], insert);
        // difficulty
        loadCell(5, colIndex, '<h3>Trip Level</h3><img src="/images/itinerary/grade-' + cellData[4] + '.gif" /><br />' + cellData[14], insert);
        // price
        loadCell(6, colIndex, '<h3>Tour cost</h3>from ' + cellData[5], insert);
        loadCell(7, colIndex, '<h3>Lodging</h3>' + cellData[9], insert);
        loadCell(8, colIndex, '<h3>Meals</h3>' + cellData[10], insert);
        // highlights
        loadCell(9, colIndex, '<h3>Highlights</h3>' + cellData[6], insert);
        // itin
        loadCell(10, colIndex, '<h3>Itinerary</h3>' + cellData[7], insert);
        // dates
        loadCell(11, colIndex, '<h3>Departures & Leaders</h3>' + cellData[11], insert);

        if (cleanUp) {
            // show the compare if the it's populated
            adjustUI();
            // adjust the widths of the top elements
            fixHeaderWidths();
        }

        return colIndex;
    };

    var removeColumn = function(key) {
        var position = jQuery.inArray(key, displayArray);
        // get the position of the element
        displayArray.splice(position, 1);
        // remove from the array
        jQuery('#viewer #top-scroller div').eq(position).remove();
        jQuery('#viewer table tr').each(function(index) {
            jQuery(this).children().eq(position).remove();
        });
    };

    var loadCell = function(rowIndex, colIndex, htmlData, insert, className) {
        var rowIndex = rowIndex - 1;
        var colData = jQuery('<td/>').html(htmlData);
        if (className) jQuery(colData).addClass(className);
        var theRow = jQuery('#viewer tr').eq(rowIndex);
        if (insert == 'after' || jQuery(theRow).children().length === 0) {
            colData.appendTo(theRow);
        } else {
            jQuery(theRow).children().eq(colIndex - 1).before(colData);
        }
    };

    var changeColumn = function(event) {
        // toggle the checkbox
        var key = event.data.whichKey;
        jQuery(this).toggleClass("selected");
        if (jQuery(this).hasClass("selected")) {
            // we're adding
            var newIndex = addColumn(key);
            // adjust the scroll
            adjustScroll(newIndex);
        } else {
            // we're removing
            removeColumn(key);
            // remove from the table
        }
        adjustUI();
        // adjust the widths of the top elements
        fixHeaderWidths();

    };

    var displayAllTrips = function() {
        var counter = 0;
        for (key in tripData) {
            counter++
            addColumn(key,(counter === tripData.length));
        }
    };

    // initialization
    if (displayArray == undefined) {
        var displayArray = [];
        jQuery('#picker li:last').addClass('last');
        // set up basic table and rows
        jQuery('#viewer table').html('<tbody><tr/><tr/><tr/><tr/><tr/><tr/><tr/><tr/><tr/><tr/><tr/></tbody>');
        jQuery('#viewer #top-scroller').html('');
        jQuery('#viewer #comp-scroller').scroll(function() {
            jQuery('#top-scroller').css('left', -this.scrollLeft);
        });
        for (key in tripData) {
            var newElm = jQuery('<li/>').html(tripData[key][1]).appendTo(jQuery('#picker ul')).bind('click', {
                whichKey: key
            },
            changeColumn);
            if (displayAll) jQuery(newElm).addClass('selected');
        }
        if (displayAll) displayAllTrips();
    };
};


/* UTILITY SCRIPTS */

function elementExists(elmIdentifier) {
    return (jQuery(elmIdentifier).length > 0);
}

var DEBUG = function(str) {
    if (window.console) console.log(str);
}

