var filtersReady, filtering = false;
var filterThrottle = 1500;
var filterTimer = null;

function bindExpandMenu(){
    $(".expand-menu dt").click(function() {
        $(this).toggleClass("open");
        $(this).next().toggle();
    });
}

function moveToTop(){
	window.location = window.location.pathname + window.location.search + '#';
}

function filterBlockUI(msg){
	$.blockUI({css: {top: '190px', width: '350px'}, fadeIn: 0, showOverlay: false, message: msg});
}

function resetTimer(){
	clearTimeout(filterTimer);
	filterTimer = startTimer(filterThrottle);
	return true;
}

function genQuery(paramName, params){
    var q = '';
    if (typeof(params) == "object"){
        for (p in params)
            q += '&' + paramName + '=' + params[p];
    }else{
        q += '&' + paramName + '=' + params;
    }
    return q;
}

function reloadAds(iframeClass){
	iframes = $(iframeClass);
	for(i = 0; i < iframes.length; i++){
	    iframes[i].src = iframes[i].src;
	}
	return true;
}


function startTimer(timeout){
	return setTimeout('doFilter(filters, {"filterMessage": "Loading results..."});', timeout);
}


function stopTimer(timerId){
	if(clearTimeout(timerId)){
		return true;
	}
	return false;
}

function bindTabClicks(){
	$(".secondary-info .tabs li").click(function() {
        // set the class of the clicked tab to selected
        var selectedTab = this.className;
        var contentSection = $(this).parent().siblings(".content");
        var contentItems = $(contentSection).children();       	
        if ($(this).hasClass("selected")) {
            return false;	
        } else {
            $(this).addClass('selected');
            $(this).siblings().removeClass('selected');	
        }
        // using the class of the clicked tab, display the element in the content section that has the same class	 		
        $(contentItems).each(function (i) {
            if ($(this).hasClass(selectedTab)) {
                $(this).css("display","block");
                $(this).siblings().css("display","none");
            } 
        });
    });
}

function setupDoubleSlider(vals,type,formatFunc,step){
    var elem = "#"+type+"-slider";
    vals[0] = parseInt(vals[0]);
    vals[1] = parseInt(vals[1]);
    
    if (vals[0] == vals[1]){
        vals[1] += 5; //pad the vals by $5 if min and max match.  This fixes an IE7 bug with the slider.
    }

    $("#"+type+"-selection").val(formatFunc(vals[0]) + ' - ' + formatFunc(vals[1]));
    $("#"+type+"-selection").focus(function(){ $(this).blur(); });

    $(elem).slider({
        orientation: 'horizontal',
	range: true,
	min: vals[0],
	max: vals[1],
	values: vals,
	step: step,
	slide: function(event, ui) {
		resetTimer();
		$(".ui-slider-handle").blur();
		$("#"+type+"-selection").val(formatFunc(ui.values[0]) + ' - ' + formatFunc(ui.values[1]));
	},
	stop: function(e, u) {
		filters[type] = ($(elem).slider("values", 0)) + ',' + ($(elem).slider("values", 1));
		filterFlights(filters, {'filterMessage': 'Filtering by '+type+'...'});
	}
    });
    return true;

}

function filterListItem(filterFunc,typeKey,item,nullChar,filterMsg){
	var item = $(item);
	if (filters[typeKey][0] == nullChar){
		filters[typeKey] = [];
	}
	if (item.attr('checked')){
		for (a in filters[typeKey]){
			if(item.val() == filters[typeKey][a])
				return false;
		}
		filters[typeKey].push(item.val()); //add a filter
	}else{
		for (a in filters[typeKey]){
			if(item.val() == filters[typeKey][a])
				filters[typeKey].splice(a, 1); //remove item filter
		}
	}
	if(!filters[typeKey].length){
		filters[typeKey] = [nullChar];
	}
	filterFunc(filters, {'filterMessage': filterMsg});
	return true;
}

function filterItems(filter, opts, resultsDivId, filterPath){
	// setup default opts for opts dictionary
	var opts = (opts == null) ? {'filterMessage': "Loading results..."} : opts;
	//display blockUI message
	filterBlockUI('<div class="uiBlockPrompt saving filter"><h2>' + opts['filterMessage'] + '</h2></div>');
	if(! $('#pages').length){
		$('#col3-c').append('<div class="module" id="paginationContainer"><span class="corner-tl"></span><span class="corner-tr"></span><span class="corner-br"></span><span class="corner-bl"></span><div id="pages"></div></div>');
	}
	$('#'+resultsDivId).html('');
	$('#pages').html('');
	$('#paginationContainer').addClass('hidden');

	if (opts['instant']){
		filtersReady = true;
		if (filterTimer){ // stop the timer if it's running
			stopTimer(filterTimer);
		}
	}else{
		if (!filterTimer){
			filterTimer = startTimer(filterThrottle);
			return false;
		}

		if (!filtersReady){
			resetTimer();
			return false;
		}
	}

	//reset filtersReady to false so we don't get two requests at once
	filtersReady = false;
	var filterQuery = '';
	for(f in filter){
		if (filter[f]){
			filterQuery += genQuery(f, filter[f]);
		}
	}

	filters['page'] = null; //reset page variable to null filter/sorting always reset to page 1

	$.ajax({
		type: 'GET',
		url: filterPath + '?searchId=' + searchId + filterQuery,
		dataType: 'html',
		cache: false,
		beforeSend: function(){
			filtering = true;
		},
		success: function(html){
			var strPage = '';
			
			$('#'+resultsDivId).html(html);
			$('#pages').html($('#ajaxPages').html());
			$('#filterHeader').html($('#ajaxFilter').html());

			if($('#pages').html())
				$('#paginationContainer').removeClass('hidden');
			if ($('#filterError').html())
				moveToTop();
			bindTabClicks();
			reloadAds('.adiframe');
		},
		complete: function(req, status){
			$.unblockUI();
			filtering = false;
		}
	});
}
