//==============================================================================
// Global functions
//==============================================================================

var resortCycleTimeout;
var resortCycleItems;
var resortCycleInterval = 20000;
var resortCycling = false;
var currN = 1;

$(document).ready(
    function () {
        //add analytics to external links
        $('a[href^="http"]').click(function() {
            _gaq.push(['_trackPageview', '/outgoing/?url=' + escape($(this).attr('href'))])
        });
        
        //switch other functionality on based on content class
        if ($('#content').hasClass('lesson-signup')) {
            $(".date-field").datepicker({dateFormat: "mm/dd/yy", changeYear: true, yearRange: '1900:2010'});
        }

        //apply dropdown widget whenever proper menu id is found
        $("#filter-resort").dropdown();
        $("#filter-category").dropdown();
        $("#filter-lodging").dropdown();
        
        //switch other functionality on based on content class
        if ($('#content').hasClass('lessons')) {
            var itemTabs = document.createElement('ul');
    		$(itemTabs).addClass('nav').addClass('tabs');
            
            $('.item-group .item').each(function(index) {
                var tab = document.createElement('li');
                if (index == 0) {
                    $(this).addClass('active');
                    $(tab).addClass('first').addClass('active');
                } else {
                    $(this).hide();
                }
                
                $(tab).bind('click', {targetN: index},  function(e) {tabNav(e.data.targetN);});
                
                //build tab control
                var tabTitleSrc = $(this).find('.item-title-' + index);
                //hide source object from which the tab is built
                $(tabTitleSrc).css('display', 'none');
                $(tab).attr('id', 'item-tab-' + index).text(tabTitleSrc.text());
                $(itemTabs).append(tab);
            });
            $('.item-group').prepend(itemTabs);
            //undo the no-flicker hide
            $('.item-group').css('display', 'block');
        }
        
        if ($('#content').hasClass('resort')) {
    		// RESORT CYCLE
    		window.resortCycleItems= $('#resort-feature-images .resort-image').length;
    		
    		if (window.resortCycleItems > 1) {
        		// build the navigation controls
        		var cyclePager = document.createElement('ul');
        		$(cyclePager).attr('id','resort-image-nav').addClass('nav');

        		for (var i=1; i <= resortCycleItems; i++) {
        			var item = document.createElement('li');
        			var itemLink = '<a href="#" onclick="resortNav(' + i + ');" >' + i + '</a>';
        			$(item).append(itemLink);
        			$(cyclePager).append(item);
        		}
        		
        		$('#resort-feature-nav').append(cyclePager);

        		// set first one active
        		$('#resort-image-nav li').eq(0).addClass('active');

        		// start the auto cycling
                window.resortCycleTimeout = setTimeout("resortCycle()", window.resortCycleInterval);
    		}
        }
    }
);

//SEARCH BOX
function submitQuery() {
  window.location = '/search?q=' + encodeURIComponent(document.getElementById('global-search-field').value);
  return false;
}

function searchFocus() {
  var queryInput = document.getElementById('global-search-field');
    if (queryInput.value == 'Search') {
        queryInput.value = '';
    }
}

function searchBlur() {
  var queryInput = document.getElementById('global-search-field');
  if (!queryInput.value) {
      queryInput.value = 'Search';
  }
}


//TAB NAVIGATION
function tabNav(targetN) {
    $('.item-group .item.active').removeClass('active').hide();
    $('.item-group .tabs .active').removeClass('active');
    $('.item-group #item-' + targetN).addClass('active').show();
    $('.item-group #item-tab-' + targetN).addClass('active');
}

//RESORT IMAGE CYCLING
function resortCycle(targetN) {
	if (window.currN >= window.resortCycleItems) {
		targetN = 1;
	} else {
		targetN = currN + 1;
	}
	
	resortSwitch(targetN);
	
	window.resortCycleTimeout = setTimeout("resortCycle(" + targetN + ")", window.resortCycleInterval);
}

function resortNav(targetN) {
	// Don't switch in the middle of an auto cycle
	if (!window.resortCycling) {
		clearTimeout(window.resortCycleTimeout);
		resortSwitch(targetN);
		window.resortCycleTimeout = setTimeout("resortCycle(" + targetN + ")", window.resortCycleInterval);
	}
}

function resortSwitch(targetN) {
	// default current item, if not set
	if (typeof(window.currN) == "undefined") {
		origN = 1;
	} else {
		origN = window.currN;
	}
	
	if (origN != targetN) {

    	var originalImageSelect = '#resort-image-' + origN;
    	var targetImageSelect = '#resort-image-' + targetN;

    	window.resortCycling = true; //lock out manual button's ability to switch in the middle of a transition

    	$(originalImageSelect).addClass('last-active');

    	// cross fade images
    	$(originalImageSelect).fadeOut('slow', function() {
    		$(originalImageSelect).removeClass('active last-active');
    	});
	
    	$(targetImageSelect).fadeIn('slow', function() {
            $(targetImageSelect).addClass('active');
    	});
	
    	// set active pager
	
    	$('#resort-image-nav .active').each(function() {$(this).removeClass('active')});
	
    	$('#resort-image-nav li').eq(targetN - 1).addClass('active');
	
    	window.currN = targetN;
	
    	window.resortCycling = false; // lock out manual switch in the middle of a transition
	
    } //if targetN != origN, otherwise no need for transition - same page
}

//DROPDOWN
//  Redirect to value contained in dropdown option
//  Pulled from http://jqueryui.com/demos/autocomplete/combobox.html
(function( $ ) {
    $.widget( "ui.dropdown", {
            _create: function() {
                    var self = this;
                    var select = this.element.hide(),
                            selected = select.children( ":selected" ),
                            value = selected.val() ? selected.text() : "";
                    var origid = select.attr('id');
                    select.attr('id', select.attr('id') + "_selector");
                    var origclass = select.attr('class');
                    var origstyle = select.attr('style');
                    var input = $( "<input readonly='readonly'>" )
                            .attr('id', origid)
                            .attr('class', origclass)
                            .insertAfter( select )
                            .val( value )
                            .autocomplete({
                                    delay: 0,
                                    minLength: 0,
                                    source: function( request, response ) {
                                            var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
                                            response( select.children( "option" ).map(function() {
                                                    var text = $( this ).text();
                                                    if ( this.value && ( !request.term || matcher.test(text) ) )
                                                            return {
                                                                    label: "<span class='" + $(this).attr('class') + "'>" + text + "</span>",
                                                                    value: text,
                                                                    option: this
                                                            }
                                            }) );
                                    },
                                    select: function( event, ui ) {
                                            ui.item.option.selected = true;
                                            //select.val( ui.item.option.value );
                                            self._trigger( "selected", event, {
                                                    item: ui.item.option
                                            });

                                            //trigger redirect to url contained in option value
                                            if (ui.item.option.value != '') {
                                                $(window.location).attr('href', ui.item.option.value);
                                            }
                                    },
                                    change: function( event, ui ) {
                                            if ( !ui.item ) {
                                                    var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
                                                            valid = false;
                                                    select.children( "option" ).each(function() {
                                                            if ( this.value.match( matcher ) ) {
                                                                    this.selected = valid = true;
                                                                    return false;
                                                            }
                                                    });
                                                    if ( !valid ) {
                                                            // remove invalid value, as it didn't match anything
                                                            $( this ).val( "" );
                                                            select.val( "" );
                                                            return false;
                                                    }
                                            }
                                    }
                            })
                            .addClass( "ui-widget ui-widget-content ui-corner-left" )
                            .click(function() {
                                    // close if already visible
                                    if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
                                            input.autocomplete( "close" );
                                            return;
                                    }

                                    // pass empty string as value to search for, displaying all results
                                    input.autocomplete( "search", "" );
                                    input.focus();
                            });

                    input.data( "autocomplete" )._renderItem = function( ul, item ) {
                            return $( "<li></li>" )
                                    .data( "item.autocomplete", item )
                                    .append( "<a>" + item.label + "</a>" )
                                    .appendTo( ul );
                    };

                    $( "<button>&nbsp;</button>" )
                            .attr( "tabIndex", -1 )
                            .attr( "title", "Show All Items" )
                            .insertAfter( input )
                            .button({
                                    icons: {
                                            primary: "ui-icon-triangle-1-s"
                                    },
                                    text: false
                            })
                            .removeClass( "ui-corner-all" )
                            .addClass( "ui-corner-right ui-button-icon" )
                            .click(function() {
                                    // close if already visible
                                    if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
                                            input.autocomplete( "close" );
                                            return;
                                    }

                                    // pass empty string as value to search for, displaying all results
                                    input.autocomplete( "search", "" );
                                    input.focus();
                            });
            }
    });
})(jQuery);

//COMBOBOX
(function( $ ) {
        $.widget( "ui.combobox", {
                _create: function() {
                        var self = this;
                        var select = this.element.hide(),
                                selected = select.children( ":selected" ),
                                value = selected.val() ? selected.text() : "";
                        var input = $( "<input>" )
                                .insertAfter( select )
                                .val( value )
                                .autocomplete({
                                        delay: 0,
                                        minLength: 0,
                                        source: function( request, response ) {
                                                var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
                                                response( select.children( "option" ).map(function() {
                                                        var text = $( this ).text();
                                                        if ( this.value && ( !request.term || matcher.test(text) ) )
                                                                return {
                                                                        label: text.replace(
                                                                                new RegExp(
                                                                                        "(?![^&;]+;)(?!<[^<>]*)(" +
                                                                                        $.ui.autocomplete.escapeRegex(request.term) +
                                                                                        ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                                                                ), "<strong>$1</strong>" ),
                                                                        value: text,
                                                                        option: this
                                                                };
                                                }) );
                                        },
                                        select: function( event, ui ) {
                                                ui.item.option.selected = true;
                                                //select.val( ui.item.option.value );
                                                self._trigger( "selected", event, {
                                                        item: ui.item.option
                                                });
                                        },
                                        change: function( event, ui ) {
                                                if ( !ui.item ) {
                                                        var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" );
                                                        var valid = false;
                                                        select.children( "option" ).each(function() {
                                                                if ( this.value.match( matcher ) ) {
                                                                        this.selected = valid = true;
                                                                        return false;
                                                                }
                                                        });
                                                        if ( !valid ) {
                                                               // add our invalid option and select it
                                                               select.append('<option selected="selected" value="' + $(this).val() + '">' + $(this).val() + '</option>');
                                                               return false;
                                                        }
                                                }
                                        }
                                })
                                .addClass( "ui-widget ui-widget-content ui-corner-left" );

                        input.data( "autocomplete" )._renderItem = function( ul, item ) {
                                return $( "<li></li>" )
                                        .data( "item.autocomplete", item )
                                        .append( "<a>" + item.label + "</a>" )
                                        .appendTo( ul );
                        }

                        $( "<button>&nbsp;</button>" )
                                .attr( "tabIndex", -1 )
                                .attr( "title", "Show All Items" )
                                .insertAfter( input )
                                .button({
                                        icons: {
                                                primary: "ui-icon-triangle-1-s"
                                        },
                                        text: false
                                })
                                .removeClass( "ui-corner-all" )
                                .addClass( "ui-corner-right ui-button-icon" )
                                .click(function() {
                                        // close if already visible
                                        if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
                                                input.autocomplete( "close" );
                                                return false;
                                        }

                                        // pass empty string as value to search for, displaying all results
                                        input.autocomplete( "search", "" );
                                        input.focus();
                                        return false;
                                });
                }
        });
})(jQuery);
