/*
-Que funcione guardar en los forms (copiar un poco de play)
recopilar 
la direccion de guardado debe estar en el boton como parametro y el id del form
bpform.update(nombreform, direccionguardado);
-CALENDARIO
-SUBIR IMAGENES
-editor de texto
- Tareas minimizadas
-precarga de elementos de bp_left. 
-gestor de aplicaciones de bp_left
(se poderian meter en un element.preload)

-permitir cargar javascript desde distintos servidores por si uno se cae
segundo servidor en google pages
*/


/*

php

urls avanzadas con parametros


*/
function loadscript (url) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);  
}

var tiempo_msj = 2000;

if (!console) {

	var console = {

		log: function(text) {},
		info: function(text) {}

	};
}





window.onload = function() { bpwin.init(); }



var bpuser = {
	getuser: function() {
		return 'anonymous';
	},

	//enviarLogin	
	enviarLogin: function() {
		var form = $('formulario');
		$('boton_submit').value="Procesando...";
		var obj = $('boton_submit');
		obj.disabled = !(obj.disabled);

		//Request
		new Ajax.Request('/user/logincheck', {
			parameters: $('formulario').serialize(true),
			requestHeaders: {Accept: 'application/json'},
			onSuccess: function(transport) {
				var json = transport.responseText.evalJSON(true);
				obj.disabled = !(obj.disabled);
				$('boton_submit').value="Login";
				if (json) {
					//$('formulario').submit();;
					window.location = '#';
				} else {
					alert('Login incorrecto');
				}
			},
			onFailure: function(transport) {
				obj.disabled = !(obj.disabled);
				alert('Error de conexión');
				$('boton_submit').value="Login";
			}
		});
		//Request
		return false;
	}
};



//FUNCIONES DE TOOLBAR



//funciones de visualizacion
//vistas en puro javascript y json
//AQUI VA UN CLASE
//podria ir en el propio json o en la plantilla


//funciones de manejo de objetos
//AQUI VA UNA CLASE
//formview,preview, ivonview, detaisview
var ViewPreview = {

	drawGrid: function(rows,cols) {
		var oTbl=document.createElement("Table");
		oTbl.className = 'bp-view-preview';
		for(i=0;i<rows;i++) {
			var  oTR= oTbl.insertRow(i);
			for(j=0;j<cols;j++) {
				var  oTD= oTR.insertCell(j);		
				oTD.InnerHTML="a ";
			}
		}
		bpwin.column.appendChild(oTbl);
	},
	clean: function() {
//var cell = document.getElementById("cell");
cell = bpwin.column;
if ( cell.hasChildNodes() ) {
	 while ( cell.childNodes.length >= 1 ) {
		  cell.removeChild( cell.firstChild );		 
	 } 
}

},
 init: function() {
this.clean();
this.drawGrid(4,7);
}


};

//tablas con orden y paginacion
//http://developer.yahoo.com/yui/datatable/




//debe manejar las dos listas toolbar y left
var bpmenu = {

	addToList: function() {
	textForListItem = document.listForm.todo.value
	if (textForListItem.length) {
		// create list item
		listElem = document.createElement("li")
		listElem.innerHTML = textForListItem

		// add list item to unordered list
		ul = document.getElementById("list").
		getElementsByTagName("ul")[0]
		ul.appendChild(listElem)
	  }
	}
};



	//form2object
	 //object2form
	 //debe levar a clase endebida (quiza como hidden input)
var bpform = {
	reset: function(class, id) {
		//comprobar si existe
		//comprobar tipos de datos como fechas
		$(formid).reset();
	},
	undo: function(class, id) {
		//TODO debe almacenar todos los cambios en algun sitio
	},
	fill: function(formid) {
		//TODO debe almacenar todos los cambios en algun sitio
	},

	insert: function(formid) {
		//TODO dosomethign
	},
	update: function(formid) {
		//TODO dosomething
	},

	//tomada de las encuestas_index.tpl
	delete2: function(item) {
		if (window.confirm("$lang[Confirm]")) {
			window.location.href = "?session=$auth[session]&uid=$auth[uid]&action=delete&id="+entry;
		}
	},

	update: function(formid) {
		var form = $(formid);
		$('boton_submit').value="Procesando...";
		var obj = $('boton_submit');
		obj.disabled = !(obj.disabled);

		//Request
		if ($('fields[id]').value == 0) {
			new Ajax.Request('/noticiasadmin/savenew', {
				parameters: $('formulario').serialize(true),
				requestHeaders: {Accept: 'application/json'},
				onSuccess: function(transport) {
					//alert(transport.responseText);
				  var json = transport.responseText.evalJSON(true);
				  obj.disabled = !(obj.disabled);
				  $('boton_submit').value="Guardar";
				  //alert(json);
					$('fields[id]').value = json;
				window.location = '/noticiasadmin/';
				},
				onFailure: function(transport) {
					obj.disabled = !(obj.disabled);
					alert('Error de conexión');
					$('boton_submit').value="Guardar";
				}
			});
		} else {
			new Ajax.Request('/noticiasadmin/saveedit', {
				parameters: $('formulario').serialize(true),
				requestHeaders: {Accept: 'application/json'},
				onSuccess: function(transport) {
					var json = transport.responseText.evalJSON(true);
					obj.disabled = !(obj.disabled);
					
					if (json) {
						window.location = '/noticiasadmin/';
						// $('boton_submit').value='Noticia actualizada';
					} else {
						$('boton_submit').value='Error actualizando noticia';
					}
					setTimeout("$('boton_submit').value='Guardar';", tiempo_msj);
				},
				onFailure: function(transport) {
					obj.disabled = !(obj.disabled);
					alert('Error de conexión');
					$('boton_submit').value='Error de conexion';
					 setTimeout("$('boton_submit').value='Guardar';", tiempo_msj);
				}
			});
		}
		//Request
		return false;
		
	},
	
	 itemdelete: function(formide) {
		new Ajax.Request( '/noticiasadmin/delete/'+id , {
			method: 'get',
			requestHeaders: {Accept: 'application/json'},
			onSuccess: function(transport) {
				var json = transport.responseText.evalJSON(true);
				if (json) {
					  window.location.reload();
					  //alert('Noticia eliminada');
					} else {
						alert('Error eliminando noticia');
					}
			}
		 }); 

		//Request
		return false;
		
	}

};


//resize and everyrhing u want
var bpimages = {};


var bpcalendar = {};


var bpconfig = {
//conecta con el servidor y con el modulo bpconfig
};
var bpuserconfig = {
//conecta con el servidor
};


function editor() {
	 tinyMCE.init({
		mode : "textareas",
		theme : "advanced",
		theme_advanced_buttons1 : "bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright, justifyfull,bullist,numlist,undo,redo,link,unlink",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style]"
	 });
}


