/* Handling the communication between php processing server and local ajax engine */

/*  Databap class */

var databap = 
{
	/* Constants defined with PHP
	 *	- pages
	 *	- vars.serv_name
	 *	- consts.opt_type_text
	 *	- consts.opt_type_select
	 *	- consts.max_size
	 *	- consts.authorized_exts
	 *	- consts.mask_folder
	 */
	
	//on load init
	init: function (defaultPage)
	{
		//Global constants
		this.consts.default_page = this.pages.chat;
		this.consts.process_url = 'index.php';
		this.consts.app_image_folder = 'images/';
		this.consts.add_code_text = 'Copier le code ici.';
		this.consts.search_box_text = 'Recherche...';
		this.consts.versionHtml = '<div id="author_box" class="author_box clickable round"><a id="item_link" href="#" target="_blank"><span id="description"></span> &bull; <span id="author_name"></span> (<span id="author_company"></span>) &bull; <span id="led"></span></a></div>';
		this.consts.maxHeight = $(window).height();
		this.consts.maxWidth = $(window).width();
		this.consts.time = (new Date()).getTime();
		
		//Global variables
		this.vars.$main = $('#main');
		this.vars.$menu = $('#menu');
		this.initVar('tmp', 'object');
		this.initVar('loading', 'boolean');
		this.initVar('pageIcon', 'string');
		this.initVar('current_page', 'string');
		this.initVar('current_user', 'object');
		this.initVar('profile_user', 'string');
		this.initVar('code', 'integer');
		this.initVar('proc_id', 'integer');
		this.initVar('doc_id', 'integer');
		this.initVar('phrase', 'string');
		this.initVar('code_container', 'string');
		this.initVar('focus', 'boolean', true);
		this.initVar('disconnected', 'boolean');
		this.initVar('mode', 'string', '');
		this.initVar('search_words', 'string');
		this.initVar('initLoaded', 'boolean');
		this.initVar('chans_list', 'object');
		
		//shortcuts
		this.$main = this.vars.$main;
		this.$menu = this.vars.$menu;
		this.consts.pageMaxHeight = databap.$main.height();
		this.consts.pageMaxWidth = databap.$main.width();		
		
		//Global Events Listeners
		this.initSearch();
		$('#form_header').submit(function(event){event.preventDefault();});
		
		//Left menu
		this.initMenu();
		
		//Events handler
		this.initEventHandlers();
		$(document).keyup(function(e){databap.onKeyUp(e);});
		$(document).keydown(function(e){databap.onKeyDown(e);});
		$(document).mouseenter(function(){databap.onMouveEnter();});
		$(document).mouseleave(function(){databap.onMouveLeave();});
		$(window).unload(function(){databap.onQuit();});
		//window.onbeforeunload = databap.onQuit;
		$(window).resize(databap.resizeMain);
		$(window).resize();
		
		//load default page
		defaultPage = databap.pages[(defaultPage in databap.pages)?defaultPage:'error'];
		databap.switchPage(defaultPage, {}, true);
	},
	
	initVar: function(varName, type, defaultValue, bForceValue)
	{
		if(typeof databap.vars[varName] === 'undefined' || bForceValue)
		{
			switch(type)
			{
				case 'boolean' :databap.vars[varName] = false;break;
				case 'string' :databap.vars[varName] = '';break;
				case 'integer' :databap.vars[varName] = 0;break;
				case 'array' :databap.vars[varName] = [];break;
				case 'object' :databap.vars[varName] = {};break;
				default:databap.vars[varName] = '';
			}
			if(defaultValue)
			{
				databap.vars[varName] = defaultValue;
			}
		}
	},
	
	tmp: function(sVarName, sType, oValue)
	{
		//Get
		if(typeof sType === 'undefined')
		{
			return (typeof databap.vars.tmp[sVarName] !== 'undefined')?databap.vars.tmp[sVarName]:'error';
		}
		//Init
		else if(sType && typeof databap.vars.tmp[sVarName] === 'undefined')
		{
			switch(sType)
			{
				case 'boolean' :databap.vars.tmp[sVarName] = false;break;
				case 'string' :databap.vars.tmp[sVarName] = '';break;
				case 'integer' :databap.vars.tmp[sVarName] = 0;break;
				case 'array' :databap.vars.tmp[varName] = [];break;
				case 'object' :databap.vars.tmp[sVarName] = {};break;
				default:databap.vars.tmp[sVarName] = '';
			}
			if(oValue)
			{
				databap.vars.tmp[sVarName] = oValue;
			}
			return databap.vars.tmp[sVarName];
		}
		//Set
		else if(typeof sType !== 'undefined' && typeof databap.vars.tmp[sVarName] !== 'undefined')
		{
			databap.vars.tmp[sVarName] = sType;
			return databap.vars.tmp[sVarName];
		}
		return null;
	},
	
	initEventHandlers: function()
	{
		//Reset specific pages event catchers
		databap.onResize = function(){};
		databap.resetSize = function(){};
		databap.onKeyUp = function(e){};
		databap.onKeyDown = function(e){};
		databap.onMouveEnter = function(){};
		databap.onMouveLeave = function(){};
		databap.onQuit = function(){};
	},
	
	initSearch: function()
	{
		$SearchInputBox = $('#form_header :input#query');
		$SearchInputBox.val(databap.consts.search_box_text);
		$SearchInputBox.css('color', databap.vars.search_words==''?'#D9E5F2':'#04357B');
		$SearchInputBox.focus
		(
			function()
			{
				if($(this).val()==databap.consts.search_box_text) $(this).val('').css('color', '#04357B');
			}
		);
		$SearchInputBox.blur
		(
			function()
			{
				if($(this).val()=='') $(this).val(databap.consts.search_box_text).css('color', '#D9E5F2');;
			}
		);
		$SearchInputBox.keyup(function(e){databap.loadSearchPage();});
		$('#form_header :input#search_btn_submit').click(function(){databap.loadSearchPage();});
	},
	
	initMenu: function()
	{
		databap.$menu.hover
		(
			databap.openMenu,
			function()
			{
				//if(typeof closeMenu == 'undefined' || closeMenu != true)
				//{
					closeMenu = true;
					if(typeof oMenuTimer != "undefined") clearTimeout(oMenuTimer);
					oMenuTimer = setTimeout(databap.closeMenu, 1000);	
				//}
			}
		);
		databap.$menu.find('#add_ln').click(function(){databap.loadAddPage();});
		databap.$menu.find('#procedure_ln').click(function(){databap.loadProcedurePage();});
		databap.$menu.find('#list_ln').click(function(){databap.loadListPage();});
		databap.$menu.find('#profile_ln').click(function(){databap.loadProfilePage();});
		databap.$menu.find('#chat_ln').click(function(){databap.loadChatPage();});
		databap.$menu.find('#options_ln').click(function(){databap.loadOptionsPage();});
		//databap.$menu.find('#doc').click(function(){databap.loadDocPage();});
		databap.$menu.find('#log_me_out_ln').click(function(){databap.logMeOut();});
		
		//Close menu on click
		databap.$menu.find('li').click(function(){closeMenu=true;if(typeof oMenuTimer != "undefined") clearTimeout(oMenuTimer);databap.closeMenu();});
		//databap.$menu.click(function(){closeMenu=true;if(typeof oMenuTimer != "undefined") clearTimeout(oMenuTimer);databap.closeMenu();});
	},
	
	openMenu: function()
	{
		//Disable closing
		closeMenu = false;
		if(typeof oMenuTimer != "undefined") clearTimeout(oMenuTimer);
		
		//If not already opened / about to open
		if(typeof openedMenu == 'undefined' || openedMenu != true)
		{
			openedMenu = true;
			databap.$menu.find('#menu_title').hide();
			
			//Main shadow
			databap.$main.fadeTo('fast', 0.5);
			
			//Switch useless button
			databap.$menu.find('.useless_button').removeClass('round').addClass('tiny_top_right');
			
			//Move menu items
			var iVPos = Math.max(0, $(window).scrollTop() - 46 - 46);
			databap.$menu.find('#menu_items').css('margin-top', iVPos);
			
			//Expand menu
			databap.$menu
			.stop()
			.animate
			(
				{width:'300px'/*, borderWidth:'10px'*/}, 
				'fast',
				function()
				{
					databap.$menu.find('#menu_box').show('fast');
				}
			);
		}
	},
	
	closeMenu: function()
	{
		if(closeMenu == true)
		{
			if(typeof oMenuTimer != "undefined") clearTimeout(oMenuTimer);
			
			//Switch uselecc button
			databap.$menu.find('.useless_button').removeClass('tiny_top_right').addClass('round');
			
			//Main shadow
			databap.$main.fadeTo('fast', 1);
			
			//Reduce menu
			databap.$menu
			.stop()
			.animate
			(
				{width:'20px'/*, borderWidth:'0'*/},
				'fast', 
				function()
				{
					databap.$menu.find('#menu_box').hide
					(
						'fast', 
						function()
						{
							databap.$menu.find('#menu_title').show('fast');
						}
					);
				}
			);
			openedMenu = false;
			closeMenu = false;
		}
	},
	
	setInitEnd: function(bEnded, bAddScrollBar)
	{
		//debug('initLoaded='+bEnded);
		databap.vars.initLoaded = bEnded;
		if(databap.vars.initLoaded===true)
		{
			//this.resizeMain();
			debug('resizing from setInitEnd');
			databap.onResize();
			//setTimeout(databap.onResize, 500);
		}
	},
	
	addDefaultValue: function($elem, sDefaultValue)
	{
		$elem.val(sDefaultValue).css('color', '#D9E5F2');
		$elem.focus
		(
			function()
			{
				if($(this).val()==sDefaultValue) $(this).val('').css('color', '#04357B');
			}
		);
		$elem.blur
		(
			function()
			{
				if($(this).val()=="") $(this).val(sDefaultValue).css('color', '#D9E5F2');;
			}
		);
	},
	
	getMainElem:function(elem)
	{
		return databap.$main.find(elem);
	},
	
	logMeOut:function()
	{
		databap.getInfo('log_me_out', function(){document.location='';});
	},
	
	//switch to a new page with animation, without processing image
	switchPage: function(sNextPage, vars, bNoFade)
	{
		switch_page = true;
		
		//Init's Start
		databap.setInitEnd(false);
		
		if(vars===undefined)
		{
			vars = {};
		}
		databap.vars.loading = true;
		$.get
		(
			databap.getPagePath(sNextPage),
			vars,
			function(data)
			{
				databap.vars.loading = false;
				if(databap.vars.current_page!='') databap.onQuit();
				databap.vars.current_page = sNextPage;
				databap.setTitle();
				databap.switchContent(data, bNoFade);
			}
		);
	},
	
	switchContent: function(sContent, bNoFade)
	{
		if(bNoFade === undefined)
		{
			//fadeout every elements
			index=1;
			var $elems = databap.$main.children();
			var count = $elems.size();
						
			$elems.fadeOut
			(
				'fast', 
				function()
				{
					$(this).remove();
					if(index==count)
					{
						$(sContent).appendTo(databap.$main);
						databap.loadInit();
					}
					else index++;
				}
			);
		}
		else if (bNoFade == true)
		{
			databap.$main.html(sContent);
			databap.loadInit();
		}
		switch_page = false;
	},
	
	loadInit: function()
	{		
		//save page icon
		this.vars.pageIcon = this.pageIcon();
		
		//Reset specific pages event catchers
		this.initEventHandlers();
		
		//Reset specific page variables
		this.initVar('tmp', 'object', {}, true);
		
		//Page specific Actions
		this.pageInit();
	},
	
	pageIcon: function(pageIcon, comment)
	{
		var $title = this.getMainElem('h1');
		if ($title.size() > 0)
		{
			if(!pageIcon)
			{
				var url = $title.css('backgroundImage');
				var image = url.slice(url.lastIndexOf('/'));
				image = image.substr(1, image.lastIndexOf(')') - 1);
				if(image.substr(image.length-1, 1)=='"') image=image.substr(0, image.length - 1); //bug chrome
				return image;
			}
			else
			{
				$title.css('backgroundImage', databap.getImagePath(pageIcon));
				if(typeof comment !== undefined)
				{
					$title.attr('title', comment);
				}
			}
		}
	},
	
	addBufferIcon: function()
	{
		this.pageIcon('processing_48.gif', 'Processing...');
	},
	
	addSuccessIcon: function()
	{
		this.pageIcon('yes_48.png', 'Op&eacute;ration r&eacute;ussie');
		setTimeout('databap.resetIcon()', 2000);
	},
	
	addFailIcon: function(sMsg)
	{
		if(!sMsg) sMsg = 'Echec de connexion. Essaie de refresh la page';
		this.pageIcon('no_48.png', sMsg);
		setTimeout('databap.resetIcon()', 5000);
	},
	
	resetIcon: function()
	{
		this.pageIcon(this.vars.pageIcon, '');
	},
	
	resizeMain: function()
	{
		//Back to the minimal size
		//databap.$main.height('auto');
		//databap.resetSize();
		//debug('Resize Main triggered');
		
		//Maximize main div height to fill up the page
		var iPageHeight = $('body').outerHeight(true);
		var iWindowHeight = $(window).outerHeight(true);
		var iDelta = iWindowHeight - iPageHeight;
		if(iDelta != 0)
		{
			databap.$main.height('+='+iDelta);
			databap.vars.$menu.height(databap.$main.height());
		}
		
		//Update size
		databap.consts.maxHeight = $(window).height();
		databap.consts.maxWidth = $(window).width();
		databap.consts.pageMaxHeight = databap.$main.height();
		databap.consts.pageMaxWidth = databap.$main.width();
		
		//Page event
		debug('resizing from resizeMain');
		databap.onResize();
	},
	
	saveForm: function(action, $form, fOnSuccess, bProcessIcon, dataType)
	{
		var sFormVars = $form.serialize();
		if(typeof bProcessIcon != 'undefined') databap.addBufferIcon();
		if(!dataType) dataType = 'text';
		
		databap.vars.loading = true;
		$.ajax
		(
			{
				type: 'POST',
				url: this.getActionLink(action),
				data: sFormVars,
				success:function(result)
						{
							databap.vars.loading = false;
							databap.vars.disconnected = false;
							if(typeof bProcessIcon != 'undefined') databap.resetIcon();
							fOnSuccess(result);
						},
				error:	function(jqXHR, textStatus, errorThrown)
						{
							databap.vars.loading = false;
							databap.vars.disconnected = true;
							debug('Error handler.js 331');
							databap.showError(textStatus);
						},
				dataType: dataType
			}
		);
	},
	
	getInfo: function(action, fOnSuccess, vars, type, fOnError, bProcessIcon)
	{
		if(!vars) vars = {};
		if(!type) type = 'html';
		if(typeof bProcessIcon != 'undefined') databap.addBufferIcon();
		
		vars['a'] = action;		
		databap.vars.loading = true;
		$.ajax
		(
			{
				url: databap.consts.process_url,
				data: vars,
				success:function(result)
						{
							if(result==databap.consts.disconnected) databap.goTo(databap.vars.current_page);
							else if((result==databap.consts.error || typeof result.success != 'undefined' && result.success==databap.consts.error) && typeof fOnError !== 'undefined') fOnError();
							else
							{
								databap.vars.loading = false;
								databap.vars.disconnected = false;
								if(typeof bProcessIcon != 'undefined') databap.resetIcon();
								fOnSuccess(result);
							}
						},
				error:	function(jqXHR, textStatus, errorThrown)
						{
							if(jqXHR.responseText==databap.consts.disconnected) databap.goTo(databap.vars.current_page);
							
							databap.vars.loading = false;
							databap.vars.disconnected = true;
							debug('Error handler.js 361');
							if(typeof bProcessIcon != 'undefined') databap.resetIcon();
							if(!fOnError)
							{
								databap.showError(textStatus);
								debug(textStatus+' '+errorThrown);
							}
							else fOnError(textStatus);
						},
				dataType: type
			}
		);
	},
	
	getSyncInfo: function(action, vars)
	{
		if(!vars) vars = {};
		vars['a'] = action;
		return $.ajax
		(
			{
				url: databap.consts.process_url,
				type: "GET",
				data: vars,
				dataType: "html",
				async:false,
				success: function(r){debug('getSyncInfo: Ok');}
			}
		).responseText;
	},
	
	showError: function(textStatus)
	{
		//debug('ERROR : '+textStatus);
		databap.addFailIcon();
	},
	
	getUserInfo: function(fOnSuccess)
	{
		if(typeof databap.vars.current_user.name == 'undefined')
		{
			databap.getInfo
			(
				'user_info',
				function(user)
				{
					databap.vars.current_user = user;
					fOnSuccess(user);
				},
				{},
				'json'
			);
		}
		else fOnSuccess(this.vars.current_user);
	},
	
	/* Loading Pages */
	
	loadProfilePage: function()
	{
		databap.vars.profile_user = '';
		databap.switchPage(databap.pages.profile);
	},
	
	loadChatPage: function()
	{
		databap.switchPage(databap.pages.chat);
	},
	
	loadOptionsPage: function()
	{
		databap.switchPage(databap.pages.options);
	},
	
	loadProcedurePage: function(iProcId)
	{
		//Reset display
		databap.vars.mode = '';
		this.vars.proc_id = 0;
		
		//load new page
		if(iProcId && iProcId>0)
		{
			this.vars.proc_id = iProcId;
		}
		databap.switchPage(databap.pages.procedure);
	},
	
	loadDocPage: function()
	{
		databap.vars.doc_id = 0;
		databap.switchPage(databap.pages.doc);
	},
	
	loadAddPage: function ()
	{
		databap.switchPage(databap.pages.add_code);
	},
	
	loadListPage: function()
	{
		databap.switchPage(databap.pages.list);
	},
	
	loadReadPage: function(idCode)
	{
		databap.vars.code = idCode;
		databap.switchPage(databap.pages.read_code);
	},
	
	loadSearchPage: function ()
	{
		if(databap.vars.current_page != databap.pages.search)
		{
			searchedWords = '';
			databap.switchPage(databap.pages.search);
		}
		else
		{
			databap.search();
		}
	},
	
	search:function()
	{
		//search words
		var searchWords = $.trim($('#query').val());
		
		//check already searched words
		if((window.searchedWords === undefined || searchedWords!=searchWords) && searchWords.length > 2)
		{
			//filter requests to not flood the server
			if(window.tempWords !== undefined && tempWords == searchWords && !databap.vars.loading)
			{
				//debug('launching search for : '+searchWords);
				
				//saving searched words
				searchedWords = searchWords;
				
				databap.addBufferIcon();
				databap.getInfo
				(
					'search',
					function(asData)
					{
						databap.$main.find('#code_container').empty();
						databap.setCodeContainer
						(
							function()
							{
								//display results
								if(asData.length==0)
								{
									databap.$main.find('#code_container').append('Aucun r&eacute;sultat trouv&eacute;.');
								}
								else
								{
									$.each
									(
										asData,
										function(id_code, code_info)
										{	
											//append container
											codeBoxId = databap.appendContainer('#code_container', id_code);
											
											//link
											$('#'+codeBoxId).click
											(
												function()
												{
													databap.vars.code = databap.getFirstElemId($(this).attr('id'));
													databap.switchPage(databap.pages.read_code);
												}
											).addClass('clickable');
											
											//append code to main and refresh id and return tag
											var idTag = databap.appendCode('#'+codeBoxId, code_info);
										}
									);
								}
								databap.addSuccessIcon();
							}
						);	
					},
					{keywords:searchWords},
					'json'
				);
			}
			else
			{
				//debug('delayed for checking : '+searchWords);
				tempWords = searchWords;
				setTimeout('databap.loadSearchPage()', 500);
			}
		}
		//else debug('same words');
	},
	
	getCodeLink: function(code)
	{
		return databap.getExternalLink('code', code);
	},
	
	getProcLink: function(nb)
	{
		return databap.getExternalLink('proc', nb);
	},
	
	getExternalLink: function(page, id)
	{
		return databap.vars.serv_name+page+'-'+escape($.trim(id));
	},
	
	appendCode: function(codeBox, info)
	{
		databap.vars.code = info.id_code;
		databap.vars.phrase = (!info.phrase)?info.id_code:info.phrase;
										//#code_reader
		$codeBox = databap.setElemTags($(codeBox), [databap.vars.code]);

		//About code
		databap.getMainElem('#'+databap.getElemTag('code_lines', databap.vars.code)).html(info.code);
		databap.getMainElem('#'+databap.getElemTag('description', databap.vars.code)).html(info.description);
		
		//About author
		databap.getMainElem('#'+databap.getElemTag('author_name', databap.vars.code)).text(info.name);
		databap.getMainElem('#'+databap.getElemTag('author_company', databap.vars.code)).text(info.company);
		databap.getMainElem('#'+databap.getElemTag('led', databap.vars.code)).text(info.led);			
	},
	
	setElemTags: function($CodeBox, aiIds, bUpdate, sType)
	{
		databap.setElemTag($CodeBox, aiIds, bUpdate, sType);
		$CodeBox.find('[id]').each(function(){databap.setElemTag($(this), aiIds, bUpdate, sType);});
		return $CodeBox;
	},
	
	setElemTag: function($Tag, aiIds, bUpdate, sType)
	{
		var sCurTagId = $Tag.attr('id');
		
		//Replace only ids existing in aiIds, keep the others
		if(bUpdate)
		{
			var aiCurTagIds = this.getElemIds(sCurTagId);
			for(i in aiIds)
			{
				aiCurTagIds[i] = aiIds[i];
			}
			aiIds = aiCurTagIds;
		}
		
		var sNewTagId = databap.getElemTag(databap.stripElemIds(sCurTagId), aiIds, sType);
		
		$Tag.attr('id', sNewTagId);
		if($Tag.attr('name') != undefined) $Tag.attr('name', sNewTagId);
	},
	
	getElemTag: function(sTag, aiIds, sType)
	{
		if(!sType) sType = 'c';
		if(typeof aiIds != 'object') aiIds = [aiIds];
		return sType+implode(databap.consts.id_sep, aiIds)+databap.consts.id_sep+sTag;
	},
	
	getFirstElemId: function(sTag)
	{
		var aiIds = this.getElemIds(sTag);
		return aiIds[0];
	},
	
	getElemIds: function(sTag)
	{
		return array_filter(explode(databap.consts.id_sep, sTag.substr(1)), isNumeric);
	},
	
	stripElemIds: function(sTag)
	{
		//var sPattern = 'c\\d+'+databap.consts.id_sep;
		var sType = sTag.substr(0, 1);
		var sPattern = this.getElemTag('', '\\d+', sType);
		if(this.checkRegExMatch(sPattern, sTag))
		{
			sTag = sTag.substr(this.getElemTag('', this.getElemIds(sTag), sType).length);
		}
		return sTag;
	},
	
	checkRegExMatch: function(sPattern, sText)
	{
		var oRegEx = new RegExp(sPattern, 'i');
		return sText.match(oRegEx);
	},

	setCodeContainer: function(fOnSuccess, containerId)
	{
		if(typeof databap.vars.code_container === 'undefined' || databap.vars.code_container == '')
		{
			databap.getInfo
			(
				'code_block',
				function(code_block)
				{
					databap.vars.code_container = code_block;
					if(containerId) databap.appendContainer(containerId);
					fOnSuccess();
				}
			);
		}
		else
		{
			if(containerId) databap.appendContainer(containerId);
			fOnSuccess();
		}
	},
	
	appendContainer: function(containerId, codeId)
	{
		if(containerId != '')
		{
			if(!codeId)
			{
				codeBoxId = 'code_reader';
				container = databap.vars.code_container;
			}
			else
			{
				codeBoxId = databap.getElemTag('code_reader', codeId);
				container = databap.vars.code_container.replace('id="code_reader"', 'id="'+codeBoxId+'"');
			}
			databap.getMainElem(containerId).append(container);
			return codeBoxId;
		}
		else
		{
			return false;
		}
	},
	
	getImagePath: function(imageName)
	{
		return 'url("'+databap.consts.app_image_folder+imageName+'")';
	},
	
	getPagePath: function(sPageName)
	{
		return databap.consts.mask_folder+sPageName+'.html?'+databap.consts.time;
	},
	
	addErrorBefore: function(msg, elem)
	{
		var msg = 'Erreur : '+msg+'.';
		databap.addMsgBefore(msg, 'error', elem);
	},
	
	addWarningBefore: function(msg, elem)
	{
		var msg = 'Attention : '+msg+'.';
		databap.addMsgBefore(msg, 'warning', elem);
	},
	
	addSuccessBefore: function(msg, elem)
	{
		var msg = 'Succ&egrave;s : '+msg+'.';
		databap.addMsgBefore(msg, 'success', elem);
	},
	
	addMsgBefore: function(msg, msgClass, elem)
	{
		var $msg = $('<p class="'+msgClass+'">'+msg+'</p>');
		$msg.hide().insertBefore(elem).slideDown('fast').delay(5000).slideUp('fast', function(){$(this).remove();});
	},
	
	setTitle: function(extra)
	{	
		if(!extra)
		{
			extra = '';
		}
		else
		{
			extra = extra+' | ';
		}
		var page = ucwords(databap.vars.current_page.replace('_', ' '));
		document.title = extra+'Databap '+chr('8226')+' '+page;
	},
	
	goTo: function(page)
	{
		window.location = this.getPageLink(page);
	},
	
	getPageLink: function(page)
	{
		return this.vars.serv_name+'?p='+page;
	},
	
	getActionLink: function(sAction, oVars)
	{
		if(!oVars) oVars = {};
		sVars = '';
		for(i in oVars)
		{
			sVars += '&'+i+'='+oVars[i];
		}
		return this.consts.process_url+'?a='+sAction+sVars;
	}
};

/* general methods */

String.prototype.stripVowelAccent = function()
{
	var sText = this;
	var rExps=
	[
		{re:/[\xC0-\xC6]/g, ch:'A'},
		{re:/[\xE0-\xE6]/g, ch:'a'},
		{re:/[\xC8-\xCB]/g, ch:'E'},
		{re:/[\xE8-\xEB]/g, ch:'e'},
		{re:/[\xCC-\xCF]/g, ch:'I'},
		{re:/[\xEC-\xEF]/g, ch:'i'},
		{re:/[\xD2-\xD6]/g, ch:'O'},
		{re:/[\xF2-\xF6]/g, ch:'o'},
		{re:/[\xD9-\xDC]/g, ch:'U'},
		{re:/[\xF9-\xFC]/g, ch:'u'},
		{re:/[\xD1]/g, ch:'N'},
		{re:/[\xF1]/g, ch:'n'}
	];
	for(var i=0, len=rExps.length; i<len; i++)
	{
		sText=sText.replace(rExps[i].re, rExps[i].ch);
	}
	return sText;
};

String.prototype.replaceAll = function(regex, text)
{
	return this.replace(new RegExp(regex, 'g'), text);
};

function switchValue(elem, value)
{
	sValue = elem.val();
	if(sValue == value)
	{
		elem.val('');
	}
	else if(sValue == '')
	{
		elem.val(value);
	}
}

function clearDefaultValue(elem, value)
{
	if(elem.val() == value)
	{
		elem.val('');
	}
}

function expand($eventElem)
{
	var tag = '.'+$eventElem.attr('id').substr(7);
	if($eventElem.hasClass('minus'))
	{
		$eventElem.removeClass('minus');
		$eventElem.addClass('plus');
		$(tag).hide('fast');
	}
	else
	{
		$eventElem.removeClass('plus');
		$eventElem.addClass('minus');
		$(tag).show('fast');
	}
}

function array_filter(arr, func)
{
	var retObj = {}, k; 
	for(k in arr)
	{
		if(func(arr[k]))
		{
			retObj[k] = arr[k];
		}
	}
 
	return retObj;
}

function isNumeric(input)
{
   return (input - 0) == input && input.length > 0;
}

function ucwords(text)
{
	return (t = text + '').replace
	(
		/^([a-z])|\s+([a-z])/g,
		function($1)
		{
			return $1.toUpperCase();
		}
	);
}

function getTimeString()
{
	var currentTime = new Date();
	var hours = currentTime.getHours();
	var minutes = currentTime.getMinutes();
	var secondes = currentTime.getSeconds();
	
	hours = sprintf(hours, 2, '0');
	minutes = sprintf(minutes, 2, '0');
	secondes = sprintf(secondes, 2, '0');

	return hours+':'+minutes+':'+secondes;
}

function sprintf(value, length, char)
{
	var buffer = '';
	missingCharsNb = Math.max(0, length - value.length);
	for(var i=0;i<=missingCharsNb;i++)
	{
		buffer += char;
	}
	
	return buffer+value;
}

function chr(codePt)
{
	if (codePt > 0xFFFF)
	{
		return String.fromCharCode(0xD800 + (codePt >> 10), 0xDC00 + (codePt & 0x3FF));
	}
	return String.fromCharCode(codePt);
}

function explode(delimiter, string, limit)
{
	var emptyArray = {0:''};
 
	if(arguments.length < 2 || typeof arguments[0] == 'undefined' || typeof arguments[1] == 'undefined') {return null;}
 
	if(delimiter === '' || delimiter === false || delimiter === null) {return false;}
 
	if(typeof delimiter == 'function' || typeof delimiter == 'object' || typeof string == 'function' || typeof string == 'object') {return emptyArray;} 
	
	if(delimiter === true) {delimiter = '1';
	}
	
	if(!limit) {return string.toString().split(delimiter.toString());}
	else
	{
		// support for limit argument
		var splitted = string.toString().split(delimiter.toString());		
		var partA = splitted.splice(0, limit - 1);
		var partB = splitted.join(delimiter.toString());
		partA.push(partB);
		return partA;
	}
}

function implode(glue, pieces)
{
	var i = '', retVal = '', tGlue = '';
	
	if(arguments.length === 1)
	{
		pieces = glue;
		glue = '';
	}
	
	if(typeof(pieces) === 'object')
	{
		if(pieces instanceof Array)
		{
			return pieces.join(glue);
		}
		else
		{
			for (i in pieces)
			{
				retVal += tGlue + pieces[i];
				tGlue = glue;
			}
			return retVal;
		}
	}
	else
	{
		return pieces;
	}
}

function file_exists(url)
{
	var req = this.window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
	if(!req)
	{
		throw new Error('XMLHttpRequest not supported');
	}
 
	// HEAD Results are usually shorter (faster) than GET
	req.open('HEAD', url, false);
	req.send(null);	if (req.status == 200)
	{
		return true;
	}
 
	return false;
}

function basename(path, suffix)
{
	var b = path.replace(/^.*[\/\\]/g, '');
	if (typeof(suffix) == 'string' && b.substr(b.length - suffix.length) == suffix)
	{
		b = b.substr(0, b.length - suffix.length);
	}
	return b;
}

/*
//Queue element
(
	function($)
	{
		$.fn.delaying = function(delay, reloadAction, minLength)
		{
			var options={delay:delay, reload_action:reloadAction, min_length:minLength};
			this.each
			(
				function()
				{
					$(this).data('tsb',new Delayer($(this), options));
				}
			);
			return this;
		};
		
		function Delayer(elem, options)
		{
			var self = this;
			var delays, min_length, previous_values, 
			temp_values, reload_action, processing_requests;
			
			this.init = function()
			{
				delays = options.delay;
				min_length = options.min_length;
				previous_values = '';
				temp_values = '';
				reload_action = options.reload_action;
				processing_requests = false;
			};
			
			this.request = function(val)
			{
				var requestOk = false;
				
				//Prevent from loading request with too few elements or twice the same request
				if(val.length > queue.min_length[id] && val != queue.previous_values[id])
				{
					//Prevent from spamming server with requests and wait for value stabilization
					if(queue.processing_requests[id] == false && val == queue.temp_values[id])
					{
						queue.previous_values[id] = val;
						requestOk = true;
					}
					else
					{
						queue.temp_values[id] = val;
						setTimeout(queue.reload_action[id], queue.delays[id]);
					}
				}
				return requestOk;
			};
		}
		
		
		
	}
)
(jQuery);
*/

function debug(text, bQuery)
{
	if(window.console) console.log(text);
}
