
$(document).ready(function() {
	//Solicitar los div ajax
	$('div[id*="ajax"]').each(function (i) {	
		if ($(this).attr("sync")) return ajax_sync_start($(this).attr("id"), $(this).attr("sync"));
		if ($(this).attr("interval")) return setInterval("ajax_interval('"+$(this).attr("id")+"')",1000*$(this).attr("interval"));
		$(this).load('index.php', {ajax: $(this).attr("id")}, function(data) {} );
		
	});
	//Interceptar los enlaces
	$("a").live("click", function(event){
		liveclick($(this), event);
	});
});

function liveclick(link, event) {
	
	href = link.attr("href");
	target = link.attr("target");
	if (target.indexOf('ajax') != -1) {
		event.preventDefault();
		href_parts = href.split("?");
		url = href_parts[0];
		params = href_parts[1];
		//params = params.split("&");
		//datos = 'ajax:ajax.RESOURCES';
		$('#'+target).load('index.php', {ajax: target, call: params} );
	}
	
}

function ajax_interval(id) {
	$("#"+id).load('index.php', {ajax: id}, function(data) {} );
}

function ajax_searching(div, reset) {
	$("#"+div).load('index.php', {ajax: div, call: $("#ajax_search").serialize()}, function(data) {
		if (reset=='reset') $("#input_search").val('');
	});
	return false;
}

function ajax_sync_start(id, interval) {
	$.post('index.php', {sync: 'start'}, function(data) {
		action = data.split(";");
		run=true;
		if (action[0] == 'DIALOG') {
			run=confirm(action[2]);
			if (run==false) {
				$.post('index.php', {sync: 'deny', resource: action[1]});
				self.close();
			}
			else $.post('index.php', {sync: 'allow', resource: action[1]});
		}
		else if (action[0] == 'LOGIN') {
			run = false;
			$.post('index.php', {ajax: 'ajax_LOGIN'}, function(data) {
				$('body').append(data); 
			});
		}
		if (run) {
			$("#"+id).load('index.php', {ajax: id});
			if (action[0] == 'SYNC'){
				setInterval("ajax_sync_interval('"+id+"', '"+action[1]+"')", 1000*interval);
				$(window).unload( function() {$.post('index.php', {sync: 'stop', resource: action[1]});});
			}
		}
	});
}

function ajax_sync_interval(id, resid) {
	$.post('index.php', {sync: 'sync', resource: resid}, function(data) {
		
	});
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

