/*
 * 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';
$.datepicker.setDefaults( {
	dateFormat : _dateFormatVisual,
	showAnim : 'fadeIn',
	altFormat : 'm/d/yy',
	onChangeMonthYear : function(year, month) {
		if ($(this).val() != '') {
			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 {
			$(this).datepicker('setDate', getFirstMonthDay());
		}
	},
	shortYearCutoff: '25'
});

function getFirstMonthDay() {
	var month = $.datepicker.formatDate('M',new Date());
	var year = $.datepicker.formatDate('yy',new Date());
	return $.datepicker.parseDate('M-d-yy', month + '-' + 1 + '-' + year);
}

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();
					}
					term = term.replace('.',''); //remplace . for '' 
					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'
		});
	}
}

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() {
	FB.XFBML.parse();
}

function highlightRefresh(){
	$("#refresh").effect("highlight", {}, 2000);	
}

function openPopup(url, windowName, width, height) {
	width = width || 800;
	height = height || 600;
	windowName = windowName || null;
	window.open(url, windowName, "width="+width+"px,height="+height+"px,status=yes,menubar=yes,titlebar=yes,scrollbars=yes,location=yes,toolbar=yes");
}

/**
 * This allows to bind objects to functions
 */
Function.prototype.bind = function(object) {
    var __method = this;
    return function() {
            return __method.apply(object, arguments);
    };
};

/**
 * Check if the string is empty
 */
String.prototype.isEmpty = function() {
	return this == '';
};

/**
 * use trim the Jquery.
 */
String.prototype.trim = function(){
    return jQuery.trim(this);
}