var $j = jQuery.noConflict();
var docReady = false; // EW.
/* Gets the location based on a short string value used within
 * other functions
 */

/*function getList(section){
    switch(section){
        case 'loc': return "#PackagesLocations";
        case 'exp': return "#PackagesExperiences"; 
    }
    return '';
}*/

/*
 * Shows/hides a list of selectable items and toggles
 * the image used to expand/collapse the list
 */
/*function toggleSelection(el_id,caller,useScrollPane){
    var cexp = $j(caller).attr('id') + " > img";    // build a query string for the image we want
    var imgel = $j("#"+cexp);                       // get the image itself
    if($j(el_id).is(":visible")){                   // list is visible
        $j(imgel).attr('src','/img/nav/collapsed.png');  // show "collapsed" arrow
        $j(el_id).stop().slideUp('fast');           // animate list to closed position
    }else{
        $j(imgel).attr('src','/img/nav/expanded.png'); // show "expanded" arrow
        $j(el_id).stop().slideDown('fast',          // animate list to open position
            // callback function to attach jScrollPane to list; called when slideDown
            // animation completes.
            function(){
                if(useScrollPane){ $j('.scroll-pane').jScrollPane(); }
            }
        );
    }
}*/

/*
 * Clear all storage and indication of present search parameters
 */
function clearSearch() {
    $j("#PackagesCategories").val(''); // clear value hidden field storing experiences
    //$j("#PackagesLocations").val('');   // clear value hidden field storing locations
    $j('.navItemSelected').removeClass('navItemSelected'); // remove selected class from selected items
    $j('.navImgToggleSingle').hide();
    $j("#selectedItemsList").html(''); // empty list of selected items (above search/clear buttons)
    $j.get('/packages/ajax_clear_search');
    return false;
}

/*
 * Checks to see if the element's name is currently part of the 
 * selected item list for that section.  Selected values are stored
 * as a pipe-delimited list of names in a hidden input field, so we just
 * check to see if the name exists within the string.
 */
function itemIsSelected(element){
    ////console.log('itemIsSelected: '+element);
    list = "#PackagesCategories";
    current = $j(list).val();
    //console.log('Current hidden field val: '+current);
    //elname = $j("#"+element).attr('id');
    return current.indexOf(element) != -1;
}

/*
 * Adds item to selected hidden field for associated section
 */
function selectItem(element){
    list = "#PackagesCategories";
    // add element's name to list, separated by pipe
    // we've already determined that this value isn't
    // present in this list, so no need to check again.
    var current = $j(list).val();
    //console.log('before addition: '+current);
    if(current.length > 0){
        current += "|";
    }
    //current += $j("#"+element).attr('id');
    current += element;
    //console.log('after addition: '+current);
    $j(list).val(current);
    addItemToSelectedList(element);
}
 
/*
 * Removes item from hidden field for associated section
 * We could probably have done this with a regular expression,
 * but using regular expressions is pretty much always wrong.
 */
function deselectItem(element){
    list = "#PackagesCategories";
    var current = $j(list).val();
    var elname = $j("#"+element).attr('id');
    //console.log('element for deselect: ');
    //console.log(elname);
    var parts = current.split('|');
    for (var i=0; i < parts.length; i++) {
        if(elname == parts[i]){
            parts.splice(i,1); break;
        }
    }
    $j(list).val(parts.join('|'));
    removeItemFromSelectedList(element);
}

/*
 * Takes item the user just clicked and copies the name and a "remove" button
 * to a separate list below the main select lists.
 */
function addItemToSelectedList(element){
    var elid = element; //$j(element).attr('id');
    var reml = element+'_remove';
    var link = $j("#"+element).html() + '&nbsp; <a href="#" id="'+reml+'"><img src="/img/nav/x.jpg" alt="X" /></a>';
    //console.log('link: '+link);
    $j("#selectedItemsList").append('<div class="removeItemLink" id="'+reml+'_parent">'+link+'<br /></div>');
    $j("#"+reml).click(function(){
        deselectItem(element); 
        return false;
    });

    if(!$j("#"+element).parent().hasClass("navSectionLabelSingle")){
        $j("#"+element).parent().addClass('navItemSelected');
    }
}

function removeItemFromSelectedList(element){
    var elid = $j("#"+element).attr('id');
    $j("#"+element).parent().removeClass('navItemSelected');
    if($j("#"+element).parent().hasClass('navSectionLabelSingle')){
        $j("#"+element+"_toggle").hide();
    }
    //$j("#"+element+"_toggle").hide();
    var remid = "#"+element+'_remove';
    var pid = remid+"_parent";
    $j(pid).remove();
}

function onSelectItemClick(element){
    if(itemIsSelected(element)){
        //console.log('deselecting');
        deselectItem(element);
    }else{
        //console.log('selecting');
        selectItem(element);
    }
}

function addClickListenersOld(){
    $j("#navLocationsList a").each(function(){
        $j(this).click(function(event){ onSelectItemClick(this,'loc'); return false; });
    });
    $j("#navExperiencesList a").each(function(){
        $j(this).click(function(event){ onSelectItemClick(this,'exp'); return false; });
    });
}


function collapseAllParents(myid){
    $j(".navSelectOptionsList").each(function(){
        id = $j(this).attr('id').split('_');
        if(id =! myid){
            if($j(this).is(":visible")){
                $j("#"+id).trigger('click');
            }
        }
    });
    //alert('collapse is done');
}

function addClickListeners(){
    $j(".navControlsTable a").each(function(){
        // these are the parent categories.  clicking these only expands/collapses the 
        // child category lists
        lid = "#"+$j(this).attr('id');
        $j(lid).click(function(event){
            event.preventDefault();
            //alert('clicked');
            id = $j(this).attr('id');
            opts = "#"+id+"_options";
            //console.log(opts);
            if($j(opts).is(":visible")){
                pth = "/img/nav/collapsed.png";
                $j(opts).slideUp('fast',function(){ $j('.navSelectListWrapper').jScrollPane(); });
            }else{
                $j(".navSelectOptionsList:visible").not("#"+id.split('_')[0]+"_options").each(function(){
                    fid = $j(this).attr('id').split('_')[0];
                    $j("#"+fid+"_options").slideUp('fast',function(){
                        $j("#"+fid+"_toggle_img").attr('src','/img/nav/collapsed.png');
                    });
                });
                $j(opts).slideDown('fast',function(){ $j('.navSelectListWrapper').jScrollPane(); });

                pth = "/img/nav/expanded.png";
            }
            $j("#"+id+"_toggle_img").attr('src',pth); 
        });

        tid = lid + "_toggle";
        $j(tid).click(function(event){
                event.preventDefault();
                myid = $j(this).attr('id').split('_')[0];
                $j("#"+myid).trigger('click');
            });
        });
        
    $j(".navigationSectionMulti li a").click(function(){
        onSelectItemClick($j(this).attr('id'));
        return false;
    });

    $j(".navControlsTableSingle a").click(
        function(){
            iid = "#"+$j(this).attr('id')+"_toggle";
            if($j(iid).is(":visible")){
                $j(iid).hide();
            }else{
                $j(iid).show();
            }

            onSelectItemClick($j(this).attr('id'));
            return false;
        });
}

function clickSelected(){
    // if existing search terms exist, mark them as selected
    if(selected_categories != ""){
        var s_cats = selected_categories.split('|');
        for (var i=0; i < s_cats.length; i++) {
            $j("#"+s_cats[i]).trigger('click');
        };
    }
    /*if(search_locations != ""){
        var s_locs = search_locations.split('|');
        for (var i=0; i < s_locs.length; i++) {
            $j("#"+s_locs[i]).trigger('click');
        };
    }
    if(search_experiences != ""){
        var s_exps = search_experiences.split('|');
        for (var i=0; i < s_exps.length; i++) {
            $j("#"+s_exps[i]).trigger('click');
        };
    }*/
}

$j(document).ready(function(){
    if(docReady){
        return;
    }

    addClickListeners();

    /* empty hidden field values for selected item storage */
    $j("#PackagesCategories").val('');

    /* form submission for keyword search */
    $j("#navKeywordSearchSubmit").bind('click',
        function() { 
            s = $j("#PackagesSearch").val();
            s = jQuery.trim(s);
            if(s.length == 0){
                window.location = searchUrl;
            }else{
                $j("#navKeywordSearchForm").submit(); 
            }
        }
    );
    /* clear seach click handler */
    $j("#navSelectionClear").bind('click', function() { clearSearch(); });

    $j("#navSelectionSearch").bind('click',
        function(event) {
            event.preventDefault();
            var s_cats = $j("#PackagesCategories").val().split('|');
            var tail = s_cats.join('/');
            base = searchUrl;
            if(tail.substr(0,1) != '/'){ base += '/'; }
            window.location = base+tail;
        }
    );

    //

    /* set hover property for list items */
    $j('.navSelectList > li').hover(
        function() { $j(this).addClass('selectOnMouseOver'); },
        function() { $j(this).removeClass('selectOnMouseOver'); }
    );

    clickSelected();


     $j(".auxNavItem").hover(
        function(){ $j(this).css('background-color','#a1a1a1'); },
        function(){ $j(this).css('background-color','#1992dc'); }
    );
    $j("#subNavContainer td").hover(
        function(){ $j(this).addClass('subNavOptionHover'); },
        function(){ $j(this).removeClass('subNavOptionHover'); }
    );
    $j("#topNavExpandMe").mouseenter(
        function(){ 
            $j("#subNavContainer").show(); 
            $j(this).parent().addClass('topNavOptionHover');
        }
    );
    $j(".auxNavItem").mouseenter(
        function(){ 
            $j("#subNavContainer").hide(); 
            $j("#topNavExpandMe").parent().removeClass('topNavOptionHover');
            $j("#topNavExpandMe").parent().addClass('topNavOption');
        }
            
    );
    $j("#subNavContainer").mouseleave(
        function(){ 
            $j("#subNavContainer").hide(); 
            $j("#topNavExpandMe").parent().removeClass('topNavOptionHover');
            $j("#topNavExpandMe").parent().addClass('topNavOption');
        }
    );

    /* click listeners for quick filters */

    $j('.navSelectListWrapper').jScrollPane();

    docReady = true;
});




