
if (!console) {

	var console = {

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

	};
}

function NewWindow(u,n,w,h,f,p,x,y){
	var win=(ws=window.screen?1:0,m=Math,C='center',R='random',M='custom',sw=screen.availWidth,sh=screen.availHeight,T=(p==C&&ws)?(sh-h)/2:(p==R&&ws)?(m.floor(m.random()*(sh-h))):(p==M)?y:100,L=(p==C&&ws)?(sw-w)/2:(p==R&&ws)?(m.floor(m.random()*(sw-w))):(p==M)?x:100,s='width='+w+',height='+h+',top='+T+',left='+L,s+=(!f||f=='')?'':','+f,window.open(u,n,s));
	if (win.focus) {
		win.focus();
	}
}


/* soporte comentarios */

function validate_email(str) {

	return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);


}

function comment_check() {
	valid = true;
	try {
		if (jQuery("#comment_name").value.length < 3) valid = false;
		if (!validate_email(jQuery("#comment_email").value)) valid = false;
		if (jQuery("#comment_content").value.length < 3) valid = false;
		if (jQuery("#comment_content").value.length > 1500) valid = false;

		if (valid)
			jQuery("#comment_submit").disabled = false;
		else
			jQuery("#comment_submit").disabled = true;

	} catch(e) {}

}


function comment_init() {

	/*
	allNodes = jQuery("#firstDiv", "secondDiv");
	for(i = 0; i < allNodes.length; i++) {
		alert(allNodes[i].innerHTML);
	}
	*/
	try {
		if (jQuery("#comment_name") != null) {
		Event.observe(jQuery("#comment_name"),'change',comment_check);
		Event.observe(document,'keypress',comment_check);


		Event.observe(jQuery("#comment_email"),'change',comment_check);

		Event.observe(jQuery("#comment_content"),'change',comment_check);
		}
	} catch(e) {}

	comment_check();
}

/*
Event.observe(window, 'load', comment_init );
*/
jQuery(document).ready(comment_init);

/* soporte menus */
function muestra(menuSelected) {
	var tablabels = document.getElementsByClassName('tablabels');
	var tablabel = tablabels[0];
	var tablabel_items = tablabel.getElementsByTagName("li");

	var tabcontents = document.getElementsByClassName('tabcontents');
	var tabcontent = tabcontents[0];
	var tabcontent_items = tabcontent.getElementsByTagName("div");

	for (var i = 0; i < tablabel_items.length; i++) {
	//	if (tablabel_items[i] != menuSelected.parentNode) {
		if (tablabel_items[i] != menuSelected) {
			tablabel_items[i].className = "";
			tabcontent_items[i].className = "tabcontent";
		  console.log(tablabel_items[i].id+' unselected');
		} else {
			//menuSelected.parentNode.className = "tablabelSelected";
			menuSelected.className = "tablabelSelected";
			tabcontent_items[i].className = "tabcontentSelected";
		  console.log(tablabel_items[i].id+' selected');
		}
	}
  return false;
}



function detectaMenu() {

	//labels
	var tablabels = jQuery('.tablabels');
	var tablabel = tablabels[0];

	if (tablabel != null) {
		var tablabel_items = tablabel.getElementsByTagName('li');
		for (var i=0; i<tablabel_items.length;i++ ) {
			 //	var destino = myEls[i].href.split('#')[1];
			 tablabel_items[i].id = 'tablabel'+i;
			 console.log('init en tablabel:'+tablabel_items[i].id);

			 tablabel_items[i].onclick = function() {
				console.log('click en '+this.id);
				muestra(this);
				return false;
			 };
			 //iniciaMenu("tabsglobal", "cuerposglobal");
			 
			 //iniciaMenu("tabsglobal", myEls[i]);
		}

		//contenidos
		var tabcontents = jQuery('.tabcontents');
		var tabcontent = tabcontents[0];
		var tabcontent_items = tabcontent.getElementsByTagName('div');
		for (i=0; i<tabcontent_items.length;i++ ) {
			 // do stuff here with myEls[i]
			 //iniciaMenu("tabsglobal", "cuerposglobal");
			 console.log('init en tabcontent:'+i);

			 tabcontent_items[i].id = 'tabcontent'+i;
			 //iniciaMenu("tabsglobal", tabcontent[i]);
		}


		//labels
		//var menu = document.getElementById('tabsglobal');
		tablabel_items[0].className = 'tablabelSelected';

		//contenidos
		//var cuerpos = document.getElementById('cuerposglobal');
		tabcontent_items[0].className = 'tabcontentSelected';
	}

}


//Event.observe(window, 'load', detectaMenu);

jQuery(document).ready(detectaMenu);
/* inicio soporte widgets */

var widget = {};

widget.init = function() {
	var bpcookie = readCookie('bpcookie');
	if (bpcookie != null )  {

		widget.detectaPortadas();
		widget.detectaColumnas();
	}
}


widget.showCode = function(item) {
	 alert('showCode '+item.item_class+' '+item.item_id);
	 //dialogo con textarea
}


widget.deletes = function(item) {
	 var bar = item.parentNode;
	 var wid = bar.parentNode;
	 var pwid = wid.parentNode;
	 //alert('delete1 '+item.item_class+' '+item.item_id);
	 //alert('delete2 '+item.item_class+' '+item.item_id);
	 console.log('delete '+bar.item_class+' '+bar.item_id);
	 pwid.removeChild(wid);
}


widget.deletes2 =function(event) {
	 var bar = this.parentNode;
	 var wid = bar.parentNode;
	 var pwid = wid.parentNode;
	 //alert('delete1 '+item.item_class+' '+item.item_id);
	 //alert('delete2 '+item.item_class+' '+item.item_id);
	 console.log('delete '+bar.item_class+' '+bar.item_id);
	 pwid.removeChild(wid);
};


widget.detectaPortadas = function() {

	//labels
	var portadas = document.getElementsByClassName('widget');
	for (var i=0; i < portadas.length; i++) {
		var item_class = portadas[i].id.split('-')[0];
		var item_id = portadas[i].id.split('-')[1];
		console.log('init portada:'+item_id);
		//portadas[i].innerHTML .= '<a href="'+id+'"></a>';



		var widgetBar = document.createElement("div");
		widgetBar.className = 'widget-bar';
		widgetBar.style.background = 'red';
		widgetBar.style.display = 'block';
		widgetBar.item_class = item_class;
		widgetBar.item_id = item_id; //quiza mejor en el widget no en la barra

		portadas[i].style.border='2px solid red !important'; //TODO cambiar clase instead
		portadas[i].style.marginTop='8px !important'; //cambiar clase instead
		portadas[i].style.marginBottom='8px !important'; //cambiar clase instead

		var newEdit = document.createElement("a");
		newEdit.href='/apd/?module=portadas&action=file_list&s1='+item_id;
		newEdit.innerHTML = 'edit '+item_class+' '+item_id;
		newEdit.style.margin = '3px';

		var newDrop = document.createElement("a");
		newDrop.href='#'
		newDrop.innerHTML = 'drop';
		newDrop.style.margin = '3px';
		newDrop.onmouseover = function(event) {
			this.parentNode.parentNode.style.background='yellow'; 
		};
		newDrop.onmouseout = function(event) {
			this.parentNode.parentNode.style.background='white';
		};

		var newDelete = document.createElement("a");
		//newDelete.href='javascript:widget.deletes(this)';
		newDelete.href='javascript:return false;';
		newDelete.onclick=widget.deletes2;
		/*
		newDelete.onclick=function(event) {
		var bar = this.parentNode;
		var wid = bar.parentNode;
		var pwid = wid.parentNode;
		//alert('delete1 '+item.item_class+' '+item.item_id);
		//alert('delete2 '+item.item_class+' '+item.item_id);
		console.log('delete '+bar.item_class+' '+bar.item_id);
		pwid.removeChild(wid);
		};
		*/

		newDelete.innerHTML = 'delete';
		newDelete.style.margin = '3px';

		var newCode = document.createElement("a");
		newCode.href='javascript:widget.showCode(this.parentNode.parentNode);';
		newCode.innerHTML = 'code';
		newCode.style.margin = '3px';

		portadas[i].insertBefore(widgetBar);
		widgetBar.appendChild(newDrop);
		widgetBar.appendChild(newEdit);
		widgetBar.appendChild(newCode);
		widgetBar.appendChild(newDelete);
		//identificador de portada
	}

}



widget.detectaColumnas = function() {

	//labels
	var portadas = document.getElementsByClassName('columna');
	for (var i=0; i < portadas.length; i++) {
		var item_class = portadas[i].id.split('-')[0];
		var item_id = portadas[i].id.split('-')[1];
		console.log('init portada:'+item_id);
		//portadas[i].innerHTML .= '<a href="'+id+'"></a>';



		var color = /*random_c*/olor('hex'); //'green'

		//boton columnas?
		var child1 = portadas[i].childNodes;
		//tbody
		for (var j=0; j < child1.length; j++) {
			var child2 = child1[j].childNodes;

			//tr
			for (var k=0; k < child2.length; k++) {
				if (child2[k].style != null)
					child2[k].style.border='1px solid '+color+' !important';
				var child3 = child2[k].childNodes;
				//td
				for (var l=0; l < child3.length; l++) {
					if (child3[l].style != null)
						child3[l].style.border='1px solid '+color+' !important';
				}
			}
		}

		//barra


		var widgetBar = document.createElement("div");
		widgetBar.className = 'widget-bar';
		widgetBar.style.background = color;
		widgetBar.style.display = 'block';
		widgetBar.item_class = item_class;
		widgetBar.item_id = item_id;

		portadas[i].style.border='2px solid '+color+' !important'; //color
		portadas[i].style.marginTop='8px !important'; //cambiar clase instead
		portadas[i].style.marginBottom='8px !important'; //cambiar clase instead

		var newEdit = document.createElement("a");
		newEdit.href='/apd/?module=portadas&action=file_list&s1='+item_id;
		newEdit.innerHTML = 'edit '+item_class+' '+item_id;
		newEdit.style.margin = '3px';

		var newDrop = document.createElement("a");
		newDrop.href='#'
		newDrop.innerHTML = 'drop';
		newDrop.style.margin = '3px';
		newDrop.onmouseover = function(event) {
			this.parentNode.parentNode.style.background='yellow'; 
		};
		newDrop.onmouseout = function(event) {
			this.parentNode.parentNode.style.background='white';
		};

		var newDelete = document.createElement("a");
		newDelete.href='javascript:widget.deletes(this.parentNode.parentNode)';
		newDelete.innerHTML = 'delete';
		newDelete.style.margin = '3px';

		var newCode = document.createElement("a");
		newCode.href='javascript:widget.showCode(this.parentNode.parentNode);';
		newCode.innerHTML = 'code';
		newCode.style.margin = '3px';

		portadas[i].insertBefore(widgetBar);
		widgetBar.appendChild(newDrop);
		widgetBar.appendChild(newEdit);
		widgetBar.appendChild(newCode);
		widgetBar.appendChild(newDelete);
		//identificador de portada
	}

}



widget.alter = function() {
		
		var bpcookie = readCookie('bpcookie');

		if (bpcookie != null )  {
		  console.log('oculta barra');
			eraseCookie('bpcookie');
			window.location.reload();
		} else {
		  console.log('muestra barra');
			createCookie('bpcookie','beta',7)
			//widget.init();
			mostrar_barra();
		}
	


};

mostrar_barra = function() {
  console.log('mostrar_barra');
	var _body = document.getElementsByTagName('body') [0];
	var newDiv = document.createElement("div");

	_body.insertBefore(newDiv);
	newDiv.id = 'layout-header1';
	newDiv.innerHTML = "link1";
}

/*
 * temporalmente down
Event.observe(window, 'load', widget.init);

Event.observe(document, 'keypress', widget.alter);
*/
/*
jQuery(document).addEventListener('keydown', function(e) {
  //	if (event.keyCode ==  186) { //a la izquierda del 1
  var code = (e.keyCode ? e.keyCode : e.which);
  console.log('tecla '+code);
    if (e.which === 112) { // F1 pressed
 
 //   if (e.which === 186) { // F1 pressed
       e.preventDefault(); // cancel the event
		widget.alter;
    }
}

*/
/* fin soporte widgets */

// @format (hex|rgb|null) : Format to return, default is integer
function random_color(format) {
	var rint = Math.round(0xffffff * Math.random());
	switch(format)	{
	case 'hex':
		return ('#0' + rint.toString(16)).replace(/^#0([0-9a-f]{6})$/i, '#$1');
		break;
	case 'rgb':
		return 'rgb(' + (rint >> 16) + ',' + (rint >> 8 & 255) + ',' + (rint & 255) + ')';
		break;
	default:
		return rint;
		break;
	}
}

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);
	}
	return null;
}

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



/*
Event.KEY_TAB

230 = altgr+a
VK_F1	70	F1 key
VK_F2	71	F2 key
VK_F3	72	F3 key
VK_F4	73	F4 key
VK_F5	74	F5 key
VK_F6	75	F6 key
VK_F7	76	F7 key
VK_F8	77	F8 key
VK_F9	78	F9 key
VK_F10	79	F10 key
VK_F11	7A	F11 key
VK_F12	7B


*/
/*
var pTag = document.getElementById("xmlObj");
pTag.appendChild(newUL);


	
for (var i = 0; i < totalDataNodes.length; i++) {
    listCreation( 'data text '+i);
}

function listCreation(data){
	//http://developer.apple.com/internet/webcontent/dom2i.html
	var pTag = document.getElementById("xmlObj");
	var ulTag = pTag.getElementsByTagName("ol").item(0);
		
	var newLI = document.createElement("li");
	var newText = document.createTextNode(data);

	newLI.appendChild(newText);
	ulTag.appendChild(newLI);
}




*/



function consultaloteria() {

	var numero = jQuery('#loteria_numero').value.replace(/\./gi, "");
	//var url = 'http://api.elpais.com/ws/LoteriaNavidadPremiados?n='+numero;
	var url = '/loteria/numero/'+numero;
	new Ajax.Request(url, {
		method:'get',
		onSuccess: function(transport){
			var json = transport.responseText.evalJSON();
			//busqueda={'numero':65000,'premio':0,'timestamp':1292960127,'status':0,'error':0}
			var resultado = jQuery('#loteria_resultado');

			if (json.error == 1) {
				resultado.innerHTML = 'Número no válido';
				return false;
			 }
			 if (json.premio == 0) {
			 resultado.innerHTML = 'Tu número no ha sido premiado';
			 } else {
			 
				resultado.innerHTML = 'Felicidades! Tienes un premio de '+json.premio+' EUR al décimo';
		  }
		}
	 });
	 return false;
}


function navegacion_init() {
            console.log('navegacion_init');
			//es mas probable q pulsen next que previous
		  if (typeof section_next != "undefined") {
prerender_url('http://'+window.location.hostname+'/'+section_next+'.php');
prerender_url_firefox('http://'+window.location.hostname+'/'+section_next+'.php');
		  }
		  if (typeof section_previous != "undefined") {
prerender_url('http://'+window.location.hostname+'/'+section_previous+'.php');
prerender_url_firefox('http://'+window.location.hostname+'/'+section_previous+'.php');
		  }
		  
		  jQuery("#cabecera").gestures({ showTrail: false, advancedShapes: false, tolerance: 50 , eventHandler: navegacion_gesto});
}

function navegacion_gesto(gesname) {
  console.log(gesname);
  
  
		  if (gesname == "E") {
              console.log('west left');
			window.location='/'+section_previous+'.php';
}
		  if (gesname == "W") {
            console.log('east right'); 
			window.location='/'+section_next+'.php';
            }   
}

jQuery(document).ready(navegacion_init);

function navegacion_checkKey(e){
     switch (e.keyCode) {
      //  case 40:
      //      alert('down');
      //      break;
      //  case 38:
      //      alert('up');
       //     break;
        case 37:
            console.log('tecla left');
		  if (typeof section_previous != "undefined")
			window.location='/'+section_previous+'.php';
            break;
        case 39:
		  if (typeof section_next != "undefined")
			window.location='/'+section_next+'.php';
            console.log('tecla right');
            break;
        default:
        //    alert('???');  
            }      
}

//if (jQuery.browser.mozilla) {
    jQuery(document).keydown(navegacion_checkKey);
//} else {
 //   jQuery(document).keydown (navegacion_checkKey);
//}
