/*
 * Global variables and general setup of components
 */
// Loading layer
var loading = $("<div class='loading'>&nbsp;</div>");
var liveSearch;

// Configure generic AJAX errors
$(document).ready(function(){
	$.ajaxSetup({
		  error: function(xmlHttp) {
	  			if (xmlHttp.status == 401) {
	  				top.location.href="/"; 
				}
			}
	});
});

//Date picker defaults
var _dateFormatVisual = 'm/dd/y';
var _dateFormat = 'm/d/yy';
var global_month = $.datepicker.formatDate('M',new Date());
var global_year = $.datepicker.formatDate('yy',new Date());
$.datepicker.setDefaults( {
	dateFormat : _dateFormatVisual,
	showAnim : 'fadeIn',
	altFormat : 'm/d/yy',
	onChangeMonthYear : function(year, month) {
		var date = new Date(year, month - 1);
		month = $.datepicker.formatDate('M', date);
		if ($("#calendar").length) {
			update_calendar(month, year);
		}
	},
	beforeShow : function(input) {
		var inputVal = $(input).val();
		if (inputVal !== "") {
			var date = $.datepicker.parseDate(_dateFormatVisual, inputVal);
			if ($("#calendar").length) {
				update_calendar($.datepicker.formatDate('M', date),
					$.datepicker.formatDate('yy', date));
			}
		} else {
			var date = $.datepicker.parseDate('M-d-yy', global_month + '-' + 1 + '-' + global_year);
			$(this).datepicker('setDate', date);
		}
	}
});

function close_guide(type){
	var guide = $('.guide');
	$(guide).slideUp('medium',function(){
		$(this).remove();
	});
	$.post('/gateway/removeGuide',{type:type});
}

function create_live_search(field, result_set, controller, options) {

	// Create a search_wrapper div to anchor.
	var search_wrapper = $(field).wrap("<div class='search_wrapper'></div>");
	var search_results = $("<div class='search_results'></div>").hide();
	search_wrapper.parents(".search_wrapper").append(search_results);
	var search_timeout = undefined;
	var default_val = "Find a city...";
	if (options && options.text) {
		default_val = options.text;
	}
	if(!field.val() || field.val().length < 3) { 
		field.val(default_val).addClass('inactive'); 
	}
	
	// Show search results upon focusing the field.
	field.focus(function(){
		if($(this).val() != default_val){
			if($(this).val().length>2){
				$(this).select();
				search_results.fadeIn('medium');
			}
		}else{
			$(this).val('');
			$(this).removeClass('inactive');
		}
	});

	// Hide search results after blurring the field.
	field.blur(function(){
		search_results.fadeOut('fast');
		var selected = $(search_results).find("a.hover");
		if($(this).val().length < 1){
			var next_input = $(this).parents().next('input[type=hidden]');
			$(this).addClass("inactive");
			$(this).val(default_val);
			
			if (options && options.clearInput) {
				options.clearInput($(next_input), true);
			} else {
				clear_input_value($(next_input));
			}
		}
	});
	
	$(this).find(".search_link").live("mouseover", function(){
		var old_link = $(this).parents().find('.hover');
		old_link.removeClass("hover");
		$(this).addClass("hover");
	});
	
	// This function sets the hidden field next to the live search field with the id from the alt
	// of the live search link. (Presumably the primary key of the record)
	$(this).find(".search_link").live('click', function(){ 
		var next_input = $(this).parents().next('input[type=hidden]');
		$(next_input).val($(this).attr("alt"));
		$(this).parents().prev('input[type=text]').val($(this).text());
		$(this).removeClass('hover');
		field.blur();
	});
	
	field.keydown(function(e){
		var key = e.keyCode;
		if (key == 9) {
			// Enter key, repeat the 'click' action
			var list = $(search_results).children("ul").children("li");
			var list_size = list.length;
			var selected = list.find(".hover");
			$(selected).trigger("click");
			liveSearchInput = $(this).parent('div.search_wrapper').children('input');
			var nextTabIndex = parseInt($(liveSearchInput).attr('tabindex'))+1;
			$('[tabindex='+nextTabIndex+']').focus();
			//$(this).blur();
			return false;
		}
	});

	
	field.keyup(function(e){
		var key = e.keyCode;
		if(key < 132 && key > 64 || key == 8 || key == 190 || key == 32){
			// The wait time for requests to the search
			var wait = 200;
			// Create a timer to buffer live search requests
			if(search_timeout != undefined){ clearTimeout(search_timeout); }
			search_timeout = setTimeout(function(){
				search_timeout = undefined;
				var term = $(field).val();
				if(term.length>2){
					if (liveSearch != null) {
						liveSearch.abort();
					}
					liveSearch = $.get("/"+controller+"/livesearch/"+result_set+"/"+term,function(data){
		    		search_results.html(data);
		    		search_results.fadeIn("fast");
		    		search_results.children("ul").children("li:first").children("a").addClass("hover");
		    	});
				}else{
					search_results.fadeOut("fast");
				}
			}, wait);
		}else if(key == 13){
			// Enter key, repeat the 'click' action
			var list = $(search_results).children("ul").children("li");
			var list_size = list.length;
			var selected = list.find(".hover");
			$(selected).trigger("click");
			$(this).blur();
			liveSearchInput = $(this).parent('div.search_wrapper').children('input');
			var nextTabIndex = parseInt($(liveSearchInput).attr('tabindex'))+1;
			$('[tabindex='+nextTabIndex+']').focus();
			return false;
		}else if(key == 27){
			field.blur();
		}else if(key == 38){
			// Up key, move up in the list
			var list = $(search_results).children("ul").children("li");
			var list_size = list.length;
			var selected = list.find(".hover");
			var has_next = selected.parent().prev().length;
			selected.removeClass('hover');
			if(has_next){
				selected.parents().prev("li").children("a").addClass("hover");
			}else{
				list.parent().children("li:last").children("a").addClass("hover");
			}
			field.focus();
		}else if(key == 40){
			// Down key, move down in the list
			var list = $(search_results).children("ul").children("li");
			var list_size = list.length;
			var selected = list.find(".hover");
			var has_next = selected.parent().next().length;
			selected.removeClass('hover');
			if(has_next){
				selected.parents().next("li").children("a").addClass("hover");
			}else{
				list.parent().children("li:first").children("a").addClass("hover");
			}
			field.focus();
		}
	});
}

 $.qu = {
    _timer: null,
    _qu: [],
    add: function(fn, context, time) {
        var setTimer = function(time) {
            $.qu._timer = setTimeout(function() {
                time = $.qu.add();
                if ($.qu._qu.length) {
                    setTimer(time);
                }
            }, time || 2);
        };

        if (fn) {
            $.qu._qu.push([fn, context, time]);
            if ($.qu._qu.length == 1) {
                setTimer(time);
            }
            return;
        }

        var next = $.qu._qu.shift();
        if (!next) {
            return 0;
        }
        next[0].call(next[1] || window);
        return next[2];
    },
    clear: function() {
        clearTimeout($.qu._timer);
        $.qu._qu = [];
    }
};

function fadeInLoading(element) {
	$(element).append(loading);
	loading.fadeIn('medium');
}
  
function fadeOutLoading(element) {
	$(element).find('.loading').fadeOut('medium', function() {
		$(element).find('.loading').remove();
	});
}

function set_panel_behavior(){
	$(".right").sortable({ 
		'items': 'div.box', 
		'handle': '.header', 
		'placeholder': 'big_placeholder', 
		'forcePlaceholderSize': true, 
		'cursor': 'move'
	});
	$(".min").live('click',function(){
		$(this).parents(".box").children('.body').slideToggle();
		if($(this).text() == "-"){
			$(this).text('+');
		}else{
			$(this).text('-');
		}
	});
}

function minimize(div){
	if($(div).children(".body:visible").length){
		$(div).children(".header").children(".min").trigger('click');
	}
}

function maximize(div){
	if(!($(div).children(".body:visible").length)){
		$(div).children(".header").children(".min").trigger('click');
	}
}


/* Accordion Functionality */
function setupAccordion(element){
	if (element == undefined || element == null) {
		$("#accordion").accordion( {
			autoHeight: false,
			collapsible: true,
			header: 'li.section_title'
		});
	} else {
		$(element).accordion( {
			autoHeight: false,
			collapsible: true,
			header: 'li.title'
		});
	}
	
	
}

/* Tabs functionality */

function setupTabs() {
	var searchIds = getSearchIds();
	$("#history").tabs('destroy');
	$("#history").tabs( {
		spinner: "<img src=\"/images/friend_indicator.gif\" style=\"margin-top:1em;\"/>",
		selected : -1,
		select : function(event, ui) {
			disableTabs(ui.index);
		},
		load: function(event, ui) {
			enableTabs();
			setupOrderCombo();
		}
	});
	$(searchIds).each(function(index, searchId){
		$("#history").tabs('url', index, "/loadSearch/" + searchId+"&page=1&order=0");
	});
}

function enableTabs() {
	$('#history').data('disabled.tabs', []);
}

function disableTabs(selectedTabIndex) {
	var tabsLength = $("#history").tabs('length');
	var toDisable = new Array(_maxTabs);
	var i = 0;
	for (var tabIndex = 0; tabIndex < tabsLength; tabIndex++) {
		if (tabIndex != selectedTabIndex) {
			toDisable[i++] = tabIndex;
		}
	}
	$('#history').data('disabled.tabs', toDisable);
}

function getSearchIds() {
	var searchIds = new Array(_maxTabs);
	var i = 0;
	$("#history a").each(function() {
		searchId = getSearchId(this);
		searchIds[i] = searchId;
		i++;
	});
	return searchIds;
}

function getSearchId(tabLink) {
	var href = $(tabLink).attr('href');
	var hrefContent = href.split("_");
	return hrefContent[hrefContent.length - 1];
}

function refreshSearch(searchId) {
	$("#search_"+searchId+" .indicator").show();
	$("#search_"+searchId).load("/refreshSearch/"+searchId, null);
}

function clear_input_value(input){
	$(input).val('');
}

function initializeStatusBar() {
	$('#StatusBar').jnotifyInizialize({
		oneAtTime: true
	});
}

function statusBarAddMessage(msg) {
	$('#StatusBar').jnotifyAddMessage({
		text: msg,
		permanent: false,
		showIcon: false,
		type: 'error'
	});
}

function forceRenderFBML() {
	// Need to update the fb:profile-pic on ajax request
	if (FB.XFBML.Host.parseDomTree) {
		setTimeout(FB.XFBML.Host.parseDomTree, 0);
	}
}