/*
 * Namespaces
 */

Nid = {};
Nid.forms = [];
Nid.forms.ajaxSubmitDisable = false;
/**
 * 
 */
Nid.updateInPlace = function(url, column, type)
{
	$('#' + column).editable({
							editBy: 'dblclick',
							type: type,
							onEdit: function(content)
							{
								$('#' + column + ' input').select();
							},
							onSubmit: function(content) {
								if (content.current == content.previous)
									return;
								
								postObject = new Object;
								postObject.column = column;
								postObject.value = content.current;
								$.post(url, postObject, function(obj){
									if (obj.status != "success")
									{
						    			$('#' + column).html(content.previous);
						    			if (obj.message)
						    				$.dialog.showAlert(obj.message, 'error', obj.title);
									}
									else
									{
						    			if (obj.message)
						    				$.dialog.showAlert(obj.message, 'info', obj.title);
										
									}
							    }, "json");
							}
						});
};

/**
 * Load ajax content
 */


Nid.get = function(action, params)
{
	var target = params['target'];
	if (target.substring(0,1) != '.' && target.substring(0,1) != '#')
		target = '#' + target;
	var data = params['data'];
	var loading = params['loading'];
	if (typeof loading === "undefined")
	{
		$(target).html('Please wait...');
	} else {
		$(loading).show();
	}
	
	postObject = new Object;
	postObject.ajax = 'true';
	postObject.breadcrumb = params['breadcrumb'];
	if (typeof(data)=='object')
	{
		for (x in data)
		{
			postObject[x] = data[x];
		};
	};
    return $.ajax({
        type: "POST",
        url: action,
        data: postObject,
        success: function(data) {

    		if (typeof params['callback'] == "function")
	    	{
	    		params['callback'](target, data);
	    	} else {
	    		$(target).html(data);
	    	}
			
			if (typeof params['scroll'] !== "undefined")
			{
				$(target).scrollTo(300);
			}
			if (typeof loading !== "undefined")
			{
				$(loading).hide();
			}
						
			if (params['target'] == 'container')
				window.location.hash = action;			
        },
        error: function (e)
        {
        	window.location.href = action;
        }
    });


    return false;
	
};

/**
 * Load json ajax 
 */

Nid.show = function(action, params)
{
	if (params['scroll'] === "undefined")
		params['scroll'] = true;
	
	var target = params['target'];
	if (target.substring(0,1) != '.' && target.substring(0,1) != '#')
		target = '#' + target;
	
	var loading = params['loading'];
	if (typeof loading === "undefined")
	{
		$(target).html('Please wait...');
	} else {
		$(loading).show();
	}
	
	var data = params['data'];
	var loading = params['loading'];
	
	postObject = new Object;
	postObject.ajax = 'true';
	
	if (typeof(data)=='object')
	{
		for (x in data)
		{
			postObject[x] = data[x];
		};
	};
    return $.post(action, postObject, 
        function(obj) {
    		if (obj.status == "success") {

    			if (obj.result)
    			{
    				if (obj.target)
    				{
    					target = obj.target;
    					if (target.substring(0,1) != '.' && target.substring(0,1) != '#')
    						target = '#' + target;
    				}
    				
    				if (typeof loading !== "undefined")
    				{
    					$(loading).hide();
    				}
    				
    				if (obj.resultAddType == 'append')
    				{
    					$(target).append(obj.result);
    				} else if (obj.resultAddType == 'prepend') {
    					$(target).prepend(obj.result);
    				} else {
    					$(target).html(obj.result);
    				}
    				
					if (params['scroll']) {
						$(target).scrollTo(300);
					}
					
					if (target == '#container') {
						window.location.hash = action;
					}
    			}
    			
    			if (obj.message && obj.title)
    				$.dialog.showAlert(obj.message, 'info', obj.title);
    			

				if (obj.redirect)
					window.location.href = obj.redirect;
				
				
    		} else {
				$.dialog.showAlert(obj, 'error', obj.title);
            	window.location.href = action;
    		}
        }
    , "json");


    return false;
	
};

/*
 * Grid Functions
 */

/*
 * FilteBox Functions
 */
Nid.FilterBox = {};
Nid.FilterBox.items = {};

Nid.FilterBox.resetSortConfig = function (key) {
	$(Nid.FilterBox.items[key].id + " a").attr('href', $(Nid.FilterBox.items[key].id + " a").attr('href').replace(".del", ".asc"));
	$(Nid.FilterBox.items[key].id + " a").attr('href', $(Nid.FilterBox.items[key].id + " a").attr('href').replace(".desc", ".asc"));
	Nid.FilterBox.items[key].action = Nid.FilterBox.items[key].action.replace(".del", ".asc");
	Nid.FilterBox.items[key].action = Nid.FilterBox.items[key].action.replace(".desc", ".asc");
	$(Nid.FilterBox.items[key].id).removeClass('ascending');
	$(Nid.FilterBox.items[key].id).removeClass('descending');
	$(Nid.FilterBox.items[key].id).addClass('sort');
};

Nid.FilterBox.changeGridOrder = function(action, prefix, key)
{	
	if (typeof prefix === "undefined")
		prefix = '';
		
	$('#' + prefix + 'gridloading').show();
	postObject = new Object;
	postObject.ajax = 'true';
	$.ajax({
        type: "GET",
        url: action,
        success: function(data) {
			$('#' + prefix + 'grid').html(data);
			$('#' + prefix + 'gridloading').hide();
			/*
			 * clear all filters:
			 */
			for (itemKey in Nid.FilterBox.items)
			{
				if (itemKey != key)
				{
					Nid.FilterBox.resetSortConfig(itemKey);
				} else {
					asc = ($(Nid.FilterBox.items[key].id + " a").attr('href').lastIndexOf(".asc") > -1);
					desc = ($(Nid.FilterBox.items[key].id + " a").attr('href').lastIndexOf(".desc") > -1);
					Nid.FilterBox.resetSortConfig(itemKey);
				}
			}
			
			if (asc)
			{
				$(Nid.FilterBox.items[key].id + " a").attr('href', $(Nid.FilterBox.items[key].id + " a").attr('href').replace(".asc", ".desc"));
				Nid.FilterBox.items[key].action = Nid.FilterBox.items[key].action.replace(".asc", ".desc");
				$(Nid.FilterBox.items[key].id).removeClass('sort');
				$(Nid.FilterBox.items[key].id).addClass('ascending');
			}
			else if(desc)
			{
				$(Nid.FilterBox.items[key].id + " a").attr('href', $(Nid.FilterBox.items[key].id + " a").attr('href').replace(".asc", ".del"));
				Nid.FilterBox.items[key].action = Nid.FilterBox.items[key].action.replace(".asc", ".del");
				$(Nid.FilterBox.items[key].id).removeClass('sort');
				$(Nid.FilterBox.items[key].id).addClass('descending');
			}
			Nid.FilterBox.items[key].isDisabled = false;
		},
        error: function (e)
        {
        	window.location.href = action;
			$('#' + prefix + 'gridloading').hide();
        }
    });
	
	return action;
};

/*
 * A sample callback!
 */
Nid.callback = function(callback, arg)
{
	if (typeof callback == "function")
		callback(arg);
};

/*
 * ajax Search plug-in:
 */
Nid.Search = {
	 forms: []
	,bind:
		function(i) {
		
			var searchForm = Nid.Search.forms[i].element;
			var config = Nid.Search.forms[i].config;
			
			// set initial value:
			Nid.Search.forms[i].selected = -1;
			
			//keyup event:
			$(searchForm).find("input").keyup(function(e) {
				var name = $(this).attr('name');

				isvalid = true;
				if (((e.keyCode < 48) || (e.keyCode >= 112)) && (e.keyCode != 46) && (e.keyCode != 8) && (e.keyCode != 0))
				{
					isvalid = false;
				}
				
				if (this.value.length > 2 && isvalid)
				{
					$(searchForm).find('label[for=' + name + ']').hide();
					if (config.action)
					{
						action = config.action;
					} else {
						action = searchForm.attr("action");
					}
					
					$.post(action, $(searchForm).serialize(), 
						function(obj) {
							if (typeof obj.results == "object")
							{
								Nid.Search.forms[i].results = obj.results;
								Nid.Search.showResult(i);
							}
						}, "json");
				} else {
					if (e.keyCode == 27)
					{
						Nid.Search.hideResult(i);
						$(searchForm).find('label[for=' + name + ']').show();
						$(this).val("");
					} else {
						//up : 38
						if (e.keyCode == 38)
						{
							Nid.Search.selectNext(i, -1);
							return false;
						} else {
							//down : 40
							if (e.keyCode == 40)
							{
								Nid.Search.selectNext(i, 1);
								return false;
							}
						}
					}
				}
				
			});
			
			$(searchForm).find("label").click(function() {
				var target = $(this).attr('for');
				$(searchForm).find('input[name=' + target + ']').focus();
				$(this).hide();
			});
			
			$(searchForm).find("input").focus(function() {
				var name = $(this).attr('name');
				var that = this;
				
				$(searchForm).find('label[for=' + name + ']').hide();
				
				$('html').keyup(function(e) {
					if (e.keyCode == 27)
					{
						Nid.Search.hideResult(i);
						$(searchForm).find('label[for=' + name + ']').show();
						$(that).val("");
					}
				});
			});
			
			$('html').click(function(e) {
				if (!$(e.target).parents().is(Nid.Search.forms[i].config.resultBox))
				{
					Nid.Search.hideResult(i);
				}
			});
			
		}
	,hideResult: function(i)
	{
		var resultBox = Nid.Search.forms[i].config.resultBox;
		
		$(resultBox).hide();
	}
	,showResult: function(i)
	{
		var resultBox = Nid.Search.forms[i].config.resultBox;
		
		$(resultBox).html("");
		if (Nid.Search.forms[i].results.length > 0)
		{
			for (index in Nid.Search.forms[i].results)
			{
				if (typeof Nid.Search.forms[i].results[index] != 'object')
				{
					$(resultBox).append(Nid.Search.forms[i].results[index]);
				}
			}
		} else {
		}
		
		Nid.Search.forms[i].results = $(resultBox + " > .result-item");
		Nid.Search.forms[i].selected = -1;
		
		$(resultBox).show();
	}
	,selectNext: function(i, direction)
	{
		if (typeof direction == 'undefined')
		{
			direction = 1;
		}
		
		var max = Nid.Search.forms[i].results.length;
		var select = Nid.Search.forms[i].selected + direction;
		var selected = Nid.Search.forms[i].selected;
		
		if (select >= max)
		{
			select = -1;
		} else {
			if (select < 0)
			{
				select = -1;
			}
		}
		
		if (selected > -1)
		{
			$(Nid.Search.forms[i].results[selected]).removeClass('select');
		}
		
		if (select > -1)
		{
			$(Nid.Search.forms[i].results[select]).addClass('select');
		}
		
		Nid.Search.forms[i].selected = select;
	}
};

$.fn.ajaxSearch = function(config) {
	var searchForm = {
						 element: this
						,config: config
					};
	
	if (config.resultBox)
	{
		$(config.resultBox).hide();
	}
	
	Nid.Search.bind(Nid.Search.forms.push(searchForm) - 1);
	
	return this;
};


