// JavaScript Document
// Scripts require jQuery Javascript Framework version 1.2.1
/* PAGE VARIABLES */
var active_pane = null;

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 emailURI = '/includes/pop-ups/email-wish-list.html';
var explainURI = '/includes/pop-ups/explain-difficulty.html';
var compareURI = '/trips/compare';

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

// trigger page refresh on browser back button
window.onbeforeunload = function() {};

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,#overview_test,#glance_test,#accommodations_test,#leaders,#comments').click(function() {
        //    jQuery('#image-set').cycle('pause');
        //});

    }
    // init Tabs - this is skipped if page doesn't contain tabs
    initTabs();

    // init Navigation
    initNavigation();
    // init Add to Wish List links
    initAddToWLinks();
    // image info rollover
    if (elementExists('.info-bug')) initImageInfo();
    // init Slideshow & image info rollover
    // initSlideshow();
    
    // init Trip Navigator
    if (jQuery("#trip-navigator").length !== 0) initTripNavigator();

	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);
	}	
});

/* load menu images */

jQuery(window).bind('load',
function() {
    var preload = [
    '/images/nav/trips-on.png',
    '/images/nav/news-on.png',
    '/images/nav/about-on.gif',
    '/images/nav/toucan-on.png',
    '/images/tf-widget/btn-delete-on.gif',
    '/images/slide-show/info-bug-on.png'
    ];
    jQuery(document.createElement('img')).bind('load',
    function() {
        if (preload[0]) this.src = preload.shift();
    }).trigger('load');
});

/* Navigation Area Initialization */

function initNavigation() {
    if (jQuery.browser.safari && (jQuery.browser.version < 522)) jQuery('#nav-bar input').addClass('safari');
    jQuery('.nav>a').hoverIntent(function() {
        showNavMenu(this);
    },
    function() {
        return false;
        // do nothing
    });
    jQuery('#nav-bar, .menu').mouseout(function() {
        startRestoreMenuTimer();
    });
    jQuery('.menu').mouseover(function() {
        if (restoreMenuTimer) clearTimeout(restoreMenuTimer);
    });
    // if (elementExists('#home-page')) jQuery('.menu').css({
        // opacity: 1
    // });
    currRollOver = jQuery('#selected > a');
}

/* Slideshow Initialization */

function initSlideshow() {
    // slideshow
    jQuery('#image-set').cycle({
        fx: 'fade',
        timeout: 6000,
        delay: 6000,
        speed: 1800,
        fit: 1,
        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').hoverIntent(function() {
        if (hideSlideInfoTimer) clearTimeout(hideSlideInfoTimer);
        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();
}

if (elementExists('#itinerary-page')) {
    jQuery('#slideshow').click(function() {
        jQuery('#image-set').cycle('resume');
    });
}

jQuery('#slide-pause').click(function() {
    jQuery('#slide-pause').css('display', 'none');
    jQuery('#slide-play').css('display', 'inline');
    jQuery('#image-set').cycle('pause');
}).hover(function() {
    jQuery(this).children('img').attr('src', '/images/itinerary/cntl-pause-on.gif');
},
function() {
    jQuery(this).children('img').attr('src', '/images/itinerary/cntl-pause.gif');
}
);

jQuery('#slide-play').click(function() {
    jQuery('#slide-play').css('display', 'none');
    jQuery('#slide-pause').css('display', 'inline');
    jQuery('#image-set').cycle('resume');
}).hover(function() {
    jQuery(this).children('img').attr('src', '/images/itinerary/cntl-play-on.gif');
},
function() {
    jQuery(this).children('img').attr('src', '/images/itinerary/cntl-play.gif');
}
);

jQuery('#slide-next').hover(function() {
    jQuery(this).children('img').attr('src', '/images/itinerary/cntl-arrow-next-on.gif');
},
function() {
    jQuery(this).children('img').attr('src', '/images/itinerary/cntl-arrow-next.gif');
});

jQuery('#slide-prev').hover(function() {
    jQuery(this).children('img').attr('src', '/images/itinerary/cntl-arrow-prev-on.gif');
},
function() {
    jQuery(this).children('img').attr('src', '/images/itinerary/cntl-arrow-prev.gif');
}
);

/* Trip Navigator Initialization */
function initTripNavigator() {
    // set the active pane
    var active_pane_cookie_setting = jQuery.cookie('active_tf_pane');
    active_pane = (active_pane_cookie_setting) ? active_pane_cookie_setting: 'tf';
    if (jQuery.browser.mozilla) {
        jQuery('div.pane-top').mousedown(function() {
            if (active_pane) jQuery('#' + active_pane + '-list').css('overflow', 'hidden');
        }).mouseup(function() {
            delayedPaneUpdate(400);
        });
        jQuery('div.pane-body>div').css('overflow', 'hidden');
        jQuery('#' + active_pane + '-list').css('overflow', 'auto');
    }
    jQuery('#trip-navigator').accordion({
        header: 'div.pane-top',
        active: false
    }).change(function(event, newheader) {
        switch (jQuery(newheader).attr('id')) {
        case 'lv-top':
            jQuery('#wl-top').removeClass('up');
            jQuery('#lv-top').removeClass('up');
            active_pane = 'lv';
            break;
        case 'wl-top':
            jQuery('#lv-top').addClass('up');
            active_pane = 'wl';
            break;
        default:
            jQuery('#wl-top').addClass('up');
            jQuery('#lv-top').addClass('up');
            active_pane = 'tf';
        }
        // set the cookie to store the active pane (session)
        jQuery.cookie('active_tf_pane', active_pane);
    });
    jQuery('#trip-navigator').activate('#' + active_pane + '-top');
    // take care of the init server side
    // set the country menu (this could be done server side but to keep the values consistent it's fine that it's done here
    jQuery('#country').clone().attr('id', 'all-countries').appendTo(jQuery('body'));
    changeRegion(jQuery("#region option:selected").attr('value'));
}

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

// fixes for strange firefox behavior where the div scrollbar bleeds through
function delayedPaneUpdate(delay) {
    timer = setTimeout('doPaneUpdate()', delay);
}

function doPaneUpdate() {
    if (active_pane) jQuery('#' + active_pane + '-list').css('overflow', 'auto');
}

// 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;
        }
        if (jQuery(this).parent().attr('class') != 'list-item') {
            if (active_pane != 'wl') {
                jQuery('#trip-navigator').activate('#wl-top');
            }
        }
        manageAddLinks(this.name, 'dim');
        jQuery(this).css('background-image', 'url(/images/spinner.gif)');
        addToWishList(this.name, this.rel, this);
    });
}

/* MENU CODE */

function showNavMenu(menuObj) {
    if (restoreMenuTimer) clearTimeout(restoreMenuTimer);
    if (jQuery(menuObj).attr('name') != jQuery(currRollOver).attr('name')) swapMenu(menuObj, currRollOver);
}

function swapMenu(newMenuLabelObj, oldMenuLabelObj) {
    // find new menuBarObj
    var newMenuName = jQuery(newMenuLabelObj).attr('name')
    // find old menuBarObj
    var oldMenuName = jQuery(oldMenuLabelObj).attr('name')
    // switch out the newMenuLabelObj image for rollOver state
    setMenuImage(jQuery(newMenuLabelObj).children('img'), newMenuName + '-roll');
    // switch out the oldMenuLabelObj image for standard state
    setMenuImage(jQuery(oldMenuLabelObj).children('img'), oldMenuName);
    // fade out the old menuBarObj
    jQuery('#' + oldMenuName).fadeOut();
    // fade in the new menuBarObj
    jQuery('#' + newMenuName).fadeIn();
    // set the current menu
    currRollOver = newMenuLabelObj;
}

function startRestoreMenuTimer() {
    if (restoreMenuTimer) clearTimeout(restoreMenuTimer);
    restoreMenuTimer = setTimeout('restoreMenuBar()', 500);
}

function restoreMenuBar() {
    var currMenuName = jQuery(currRollOver).attr('name')
    if (jQuery(currRollOver).attr('className') != "selected") {
        // only restore if it's not the selected menu
        // restore the currMenu to it's prestine state
        setMenuImage(jQuery(currRollOver).children('img'), currMenuName);
        jQuery('#' + currMenuName).fadeOut();
        // restore the selectedMenu to it's prestine "selected" state
        setMenuImage(jQuery('#selected img'), jQuery('#selected img').attr('name') + '-on');
        jQuery('#' + jQuery('#selected>a').attr('name')).fadeIn('fast');
    }
    currRollOver = jQuery('#selected > a');
}

function setMenuImage(obj, imgName) {
    jQuery(obj).attr('src', '/images/nav/' + imgName + '.gif');
}

/* SEARCH FIELD */

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

/* 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();
        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() {
            displaySection(this.id);
        }).hover(function() {
            hilightTab(this.id, true);
        },
        function() {
            hilightTab(this.id, false);
        });
    }
}

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) {
    DEBUG('itinCode = ' + itinCode + ' itinName = ' + itinName);
    // debug
    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);
    setAddLinks(jQuery('#lv-' + itinCode).children('.add-btn'), 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) {
    DEBUG('SENDING: itinCode = ' + itinCode);
    // debug
    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');
}

/* POP-UP CODE */

function displayPopup(key, URI, title) {
    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
    jQuery('#image-set').cycle('resume');
}

/* EMAIL WISH LIST */
function addRecipient() {
    var keys = ['rec-first', 'rec-last', 'rec-email'];
    // array of strings to use below
    var totalRows = jQuery('table#recipients tbody tr').length;
    if (totalRows < 3) {
        var newRow = jQuery('table#recipients tbody tr:last').clone();
        jQuery(newRow).find('input').each(function(index) {
            this.value = '';
            this.id = keys[index] + '-' + (totalRows + 1);
        });
        jQuery('table#recipients tbody').append(newRow);
        setShadow("#pop-email-wish-list .pop-up");
    }
    if (totalRows > 1) jQuery('#add-recipient-btn').addClass('dim');
}

function emailWishList() {
    if (wishListItemsExist()) displayPopup('email-wish-list', emailURI, 'Email Wish List');
}

function explainDifficulty() {
    displayPopup('explain-difficulty', explainURI, 'Explain Difficulty');
}

function sendEmail() {
    // send email code goes here;
    }

function previewEmail() {
    var emailText = 'Dear ' + jQuery('#rec-first-1') + ' ' + jQuery('#rec-first-1') + ',<br/>';
    emailText = 'Dear ' + jQuery('#rec-first-1') + ' ' + jQuery('#rec-first-1') + ',<br/>';
    jQuery('#email-edit').slideUp();
    jQuery('#email-preview').slideDown('normal',
    function() {
        jQuery("#pop-email-wish-list .pop-up").redrawShadow();
    });
}

function editEmail() {
    jQuery('#email-preview').slideUp();
    jQuery('#email-edit').slideDown('normal',
    function() {
        jQuery("#pop-email-wish-list .pop-up").redrawShadow();
    });

}

function messageReady() {
    // function does not check email validity, that is done below
    return (senderValid() && recipientValid());
}

function senderValid() {
    return ((jQuery('#email-edit #first').val() != '') && (jQuery('#email-edit #last').val() != '')
    && (jQuery('#email-edit #email').val() != ''));
}

function recipientValid() {
    if (jQuery('#email-edit #rec-first.1').val() != '') {
        return (jQuery('#email-edit #rec-last-1').val() != '') && (jQuery('#email-edit #rec-email-1').val() != '');
    } else if (jQuery('#email-edit #rec-first-2').length && jQuery('#email-edit #rec-first-2').val() != '') {
        return (jQuery('#email-edit #rec-last-2').val() != '') && (jQuery('#email-edit #rec-email-2').val() != '');
    } else if (jQuery('#email-edit #rec-first-3').length && jQuery('#email-edit #rec-first-3').val() != '') {
        return (jQuery('#email-edit #rec-last-3').val() != '') && (jQuery('#email-edit #rec-email-3').val() != '');
    }
    return false;
}

/* 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>Difficulty</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;
        DEBUG(key);
        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);
}
