/*******************************************
 * Funciones de AJAX para las ligas publicas
 *******************************************/
leagueXML			= null;
leagueContent		= null;
leaguePaginate		= null;
leagueStatus		= null;

function getIEVersionNumber() {
    var ua = navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE ");
    
    if (MSIEOffset == -1) {
        return 0;
    } else {
        return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
    }
}

/**
 * 
 * Funcion para crear instancia de Ajax
 * @author Diego Olmedo
 */
  function crearInstancia(){
                var XMLHttp = null;
                if (window.XMLHttpRequest) {             
                    return new XMLHttpRequest();
                }else if (window.ActiveXObject) {             
                    var versiones = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "Msxml2.XMLHTTP.3.0", "Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];
                        for (var i = 0; i < versiones.length; i++) {
                            try {
                                XMLHttp = new ActiveXObject(versiones[i]);
                                if (XMLHttp) {
                                    return XMLHttp;
                                    break;
                                }
                                else 
                                    if (!XMLHttp) {
                                        alert('NO_SE_PUDO_CREAR_LA_INSTANCIA');
                                    }
                            } 
                            catch (e) {};
                        }

                    }

}


/**
 * 
 * FUNCIONES PARA ALERTAS PERSONALIZADOS
 * 
 */
//funcion para evitar conflictos con prototype
  
  if(typeof(jQuery)!="undefined"){
var $j = jQuery.noConflict();
  }
function alertSG2(txt, title, clase) {
	if(getIEVersionNumber() > 6 || getIEVersionNumber()==0 ) {
		try {
		if(typeof(clase)!="undefined"){
			$j.alerts.dialogClass = clase;
			}
		if(title=="undefined"){
			title="Error";
		}	 
        		jAlert(txt, title);
        		$j.alerts.dialogClass = null; 
		} catch (e) {
		    alert(e);  
			alert(txt);
		}
	}else{
		
		alert(txt);
	}
}


function confirmSG2(txt, title, clase, okText, cancelText, func) {
	if(getIEVersionNumber() > 6 || getIEVersionNumber()==0 ) {
			
		try {
	    	$j.alerts.cancelButton	 =cancelText;
	    	$j.alerts.okButton	     =okText;
	    	$j.alerts.dialogClass = clase; 
	        jConfirm(txt, title, func);
	        $j.alerts.dialogClass = null; 
	        
	    } catch (e) {
	    	alert(e);
	    	confirm(txt, title);
	    }
	}else{
		
		confirm(txt);
	}
}

function promptSG2(txt, input, title, clase, func){
    
	if(getIEVersionNumber() > 6 || getIEVersionNumber()==0 ) {
			
		try {
	    	$j.alerts.dialogClass = clase;
	        jPrompt(txt, input, title, func);
	    } catch(e) {
	        prompt(txt, input, title);
	    }
	}else{
		
		prompt(txt, input, title);
	}

}

/********************** FIN DE FUNCIONES DE ALERTAS PERSONALIZADAS ***************/

function defineObjects() 
{
	leagueJoined		= document.getElementById('joined');
	leagueContent		= document.getElementById('content_league');
	leaguePaginate		= document.getElementById('paginate');
	leagueStatus		= document.getElementById('status');
}

function loadJoined() 
{
	if(leaguesJoined.length == 0) {
		leagueHTML	 = "<table width=\"620\" border=\"0\" align=\"center\" cellpadding=\"6\" cellspacing=\"0\">\r\n";
		leagueHTML	+= "  <tr><td height=\"30\" class=\"arial12_azul\">NO_ESTAS_PARTICIPANDO_EN_NINGUNA_LIGA_PUBLICA</td></tr>\r\n";
		leagueHTML	+= "</table>";
	}else{
		leagueHTML	 = "<table width=\"620\" border=\"0\" align=\"center\" cellpadding=\"6\" cellspacing=\"0\">\r\n";
		leagueHTML	+= "  <tr class='separador_h_puntos'>";
		leagueHTML	+= "    <th width=\"240\" height=\"30\" >LIGA:</th>\r\n";
		leagueHTML	+= "    <th width=\"104\"  align='center'>PARTICIPANTES</th>\r\n"
		leagueHTML	+= "    <th width=\"140\" align=\"right\" >CREADOR</th>\r\n"
		leagueHTML	+= "    <th width=\"100\" align=\"right\" >ESTADO</th>\r\n"
		leagueHTML	+= "  </tr>";

		for(index = 0; index < leaguesJoined.length; index++) {
			leagueHTML	+= "  <tr>\r\n";
			leagueHTML	+= "    <td width=\"240\" height=\"30\" class=\"arial12_azul\"><strong>" + leaguesJoined[index].title + "</strong></td>\r\n";
			leagueHTML	+= "    <td width=\"104\" class=\"arial12_gris01\" align='center'>" + leaguesJoined[index].quantity + " </td>\r\n"
			leagueHTML	+= "    <td width=\"140\" align=\"right\" class=\"arial11\">" + leaguesJoined[index].admin + "</td>\r\n"
			leagueHTML	+= "    <td width=\"100\" align=\"right\" class=\"arial11\"><a href=\"liga_resultados.php?ligaid=" + leaguesJoined[index].id + "\" class=\"arial12_gris01\">INGRESAR</a></td>\r\n"
			leagueHTML	+= "  </tr>\r\n";
		}

		leagueHTML	+= "</table>\r\n";
	}
	

	leagueJoined.innerHTML	= leagueHTML;
}

function loadJoined()
{

}



function loadContent(search, page) 
{
	// Clean Status
	
	leagueStatus.innerHTML		= "";
	if(search) {
		leagueContent.innerHTML	= "<table width=\"100%\"><tr><td height=\"170\" align=\"center\" valign=\"center\" class=\"arial12_azul\"><img src=\"images/loading.gif\"><br><b>BUSCANDO \"" + search + "\"...</b></td></tr></table>";
	}else{
		leagueContent.innerHTML="<table width=\"100%\"><tr><td height=\"170\" align=\"center\" valign=\"center\" class=\"arial12_azul\"><img src=\"images/loading.gif\"><br /><b>CARGANDO ...</b></td></tr></table>";
	}

	if(window.XMLHttpRequest) { AJAX = new XMLHttpRequest(); } else if(window.ActiveXObject) { AJAX = new ActiveXObject('Microsoft.XMLHTTP'); }

	AJAX.onreadystatechange	= function() { createXML(search, page); };
	AJAX.open("POST", "ligas_publicas.php", true);
	AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	AJAX.send("ajax=true&search=" + search + "&page=" + page);
}

function createXML(search, page) {
	if((AJAX.readyState == 4) && (AJAX.status == 200)) {
		if(window.ActiveXObject) {
			leagueXML		= new ActiveXObject("Microsoft.XMLDOM");
			leagueXML.async		= false;

			leagueXML.loadXML(AJAX.responseText);
		}else{
			leagueXML		= new DOMParser();
			leagueXML		= leagueXML.parseFromString(AJAX.responseText, "text/xml");
		}

		if(leagueXML) {
		
			// Total de ligas
			leagueTotal	= leagueXML.childNodes.item(0).attributes.item(0).value;

			// Comienzo de diseño
			leagueHTML 	 = "<table width=\"620\"  border=\"0\" align=\"center\" cellpadding=\"0\" cellspacing=\"0\" class=\"backtabla_liga\">\r\n";
			
			if(search != '') { leagueHTML += "  <tr><td height=\"25\"><img src=\"images/ttl_resultadobusqueda.gif\" width=\"201\" height=\"21\" /></td></tr>\r\n"; }else{ leagueHTML += "  <tr><td height=\"25\"><img src=\"images/ttl_listado.gif\" width=\"190\" height=\"21\" /></td></tr>\r\n"; }
				
			leagueHTML	+= "</table>\r\n";

			if(search != '') {
				leagueHTML	+= "<table width=\"620\" border=\"0\" align=\"center\" cellpadding=\"6\" cellspacing=\"0\">\r\n";
				leagueHTML	+= "  <tr><td height=\"25\" class=\"arial12_negro\">TU_BUSQUEDA_POR <span class=\"arial12_azul\"><strong>" + search + "</strong></span> HA_OBTENIDO <span class=\"arial12_azul\">" + leagueTotal + " RESULTADOS</span></td></tr>\r\n";
				leagueHTML	+= "</table>\r\n";
			}

			if(leagueXML.childNodes.item(0).childNodes.length >= 0) {
				leagueHTML	+= "<table width=\"620\" border=\"0\" align=\"center\" cellpadding=\"6\" cellspacing=\"0\">";
				leagueHTML	+= "  <tr class='separador_h_puntos'>";
				leagueHTML	+= "    <th width=\"240\" height=\"30\" >LIGA:</th>\r\n";
				leagueHTML	+= "    <th width=\"104\"  align='center' >PARTICIPANTES</th>\r\n"
				leagueHTML	+= "    <th width=\"140\" align=\"right\" >CREADOR</th>\r\n"
				leagueHTML	+= "    <th width=\"100\" align=\"right\" >ESTADO</th>\r\n"
				leagueHTML	+= "  </tr>";
				for(index = 0; index < leagueXML.childNodes.item(0).childNodes.length; index++) {
					leagueID	= leagueXML.childNodes.item(0).childNodes.item(index).attributes.item(0).value;
					leagueTitle	= leagueXML.childNodes.item(0).childNodes.item(index).attributes.item(1).value;
					leagueQuantity	= leagueXML.childNodes.item(0).childNodes.item(index).attributes.item(2).value;
					leagueAdmin	= leagueXML.childNodes.item(0).childNodes.item(index).attributes.item(3).value;

					// Verify user in league
					leagueAction	= "<span onclick=\"joinLeague(" + index + ", '" + search + "', " + page + ");\" class=\"arial11\" style=\"cursor: pointer;\">PARTICIPAR</span>";

					for(subindex = 0; subindex < leaguesJoined.length; subindex++) { if(leaguesJoined[subindex].id == leagueID) { leagueAction = "<span  class=\"arial11_gris01\">YA_PARTICIPAS</span>"; break; } }

					// Generate Row
					leagueHTML += "<tr><td width=\"235\" height=\"30\" class=\"arial12_azul\"><strong>" + leagueTitle + "</strong></td><td width=\"106\"  align='center' class=\"arial12_gris01\">" + leagueQuantity + " </td><td width=\"132\" align=\"right\" class=\"arial12_gris01\">" + leagueAdmin + "</td><td width=\"99\" align=\"right\"><strong>" + leagueAction + "</strong></td></tr>";
				}

				leagueHTML	+= "</table>";

				leagueContent.innerHTML	= leagueHTML;

				// Paginator
				var beginPage	= page;
				var endPage	= page;
				var actualPage	= page;
				var totalPage	= Math.ceil(leagueTotal / leagueRecords);

				index		= 1;

				while(index <= 7) {
					if((beginPage - 1) <= 0 && (endPage + 1) >= totalPage) { index++; }

					if((beginPage - 1) >= 0) { beginPage--; index++; }
					if((endPage + 1) < totalPage) { endPage++; index++; }
				}

				leaguePaginate.innerHTML = "<span class=\"arial11\">P&aacute;ginas : ";

				for(index = beginPage; index <= endPage; index++) {
					if(actualPage == index) {
						leaguePaginate.innerHTML += "<b>" + (index + 1) + "<b>";
					}else{
						leaguePaginate.innerHTML += "<a href=\"javascript: loadContent('" + search + "', " + index + ");\" class=\"arial11\">" + (index + 1) + "</a>";
					}

					if((index + 1) <= endPage) { leaguePaginate.innerHTML += " <span class=\"arial11\">•</span> "; }
				}

				leaguePaginate.innerHTML += "</span>";
			}else{
				leaguePaginate.innerHTML  = "";
			}
		}
	}
}

function joinLeague(indexData, search, page) 
{
	leagueData	= leagueXML.childNodes.item(0).childNodes.item(indexData).attributes;
	confirmSG2("PREGUNTA_LIGA_PUBLICA_PARTICIPAR_EN_LIGA", "CONFIRMACION_DE_PARTICIPACION_A_LIGAS_PUBLICAS","jLP", "SI", "NO", function(r){
		if(r==true){
			if(window.XMLHttpRequest) { 
				JOIN = new XMLHttpRequest(); 
			} else if(window.ActiveXObject) { 
				JOIN = new ActiveXObject('Microsoft.XMLHTTP'); 
			}
		
			JOIN.onreadystatechange	= function() { 
				if((JOIN.readyState == 4) && (JOIN.status == 200)) {
					if(JOIN.responseText == "") {
					leaguesJoined.push({'id':leagueData.item(0).value, 'title':leagueData.item(1).value, 'quantity':(parseInt(leagueData.item(2).value) + 1), 'admin':leagueData.item(3).value});

					loadJoined();

					loadContent(search, page);

					leagueStatus.innerHTML	= "<table width=\"620\"  border=\"0\" align=\"center\" cellpadding=\"5\" cellspacing=\"0\"><tr><td height=\"57\" align=\"center\" class=\"backtabla_alert\"><span class=\"arial16_blanco\">HAS_SIDO_AGREGADO_A_LA_LIGA <strong>" + leagueData.item(1).value + "</strong></span></td></tr></table>";
				}else{
					window.location	= '';
				}
			}
		};

		JOIN.open("POST", "ligas_publicas.php", true);
		JOIN.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		JOIN.send("ajax=true&join=" + leagueData.item(0).value);
	}
		});

}