document.write('<script type="text/javascript" src="/vistas/js/prototype.js"></script>');
document.write('<script type="text/javascript" src="/vistas/js/appobj.js"></script>');

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/g,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/g,"");
}

//funcion que permite en una caja de texto determinada, el ingreso de numeros unicamente
/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function changeFinzalizedRoundsCat (strCat, strURLWebservices, strSitioRequest) {
	var aleatorio = Math.round(Math.random()*10000);
	strUrlEmbebida = 'http://'+strURLWebservices+'/modules/ws/gettandasfinalizadas.php?sitiorequest='+strSitioRequest+'&strCat='+strCat+'&ale='+aleatorio;
	strUrlEmbebida = strUrlEmbebida.replace( new RegExp("[?]","g"),"PREG");
	strUrlEmbebida = strUrlEmbebida.replace( new RegExp("[&]","g"),"AMP");
	var strUrl = '/modules/ws/geturlajax.php?wsUrl='+strUrlEmbebida;
	AppObj.Ajax.updaterAjax(strUrl,'div_finalized');
}

function openPPCEV(arrRace,strMod) {
	strMod = typeof arrRace == 'undefined' ? '' : strMod;
	document.location.href = '/modules/ppcev/?arrrace=' + Object.toJSON(arrRace) + '&show=' + strMod;
}

function changeHomeNewsCat(intCat) {
	AppObj.Ajax.updaterAjax('/modules/news/ajax_home_news.php?cat=' + intCat ,'div_newsflash');
	ChangeIconCat(intCat, 'news_home');
}

function $V (object) {
	var obj = $(object);
	if (obj) return obj.value; 
	return obj;
}

function changeTop48NewsCat (intIdCat) {
	AppObj.Ajax.updaterAjax('/modules/news/ajax_more_news.php?cat=' + intIdCat + '&home=yes' ,'div_more_news_48');
	ChangeIconCat(intIdCat, 'news_top48');
}

function changeTrastiendaNewsCat (intIdCat) {
	AppObj.Ajax.updaterAjax('/modules/news/ajax_trastienda_news.php?cat=' + intIdCat + '&home=yes' ,'div_trastienda');
}

var nav4 = window.Event ? true : false;

function solonumeros ( evt ) { 
	var key = nav4 ? evt.which : evt.keyCode;
	return (key <= 13 || (key >= 48 && key <= 57));
}
function solonumerosdecimales ( evt ) { 
	var key = nav4 ? evt.which : evt.keyCode;
	return (key <= 13 || (key >= 48 && key <= 57) || key == 46 );
}

function MM_openBrWindow ( theURL , winName , features ) { //v2.0
	if(features=="") features="location=0,status=1,scrollbars=1,width=800,height=600";	
	window.open ( theURL , winName , features ) ;
}

function Imprimir() {
	window.print();
}

function Cerrar() {
	window.close();
}

function Volver() {
	window.history.go(-1);
}

function VerificarForm ( pObj , pControl , pTipo ) {
	pObj = document.getElementById ( pObj ) ;
	if(pObj==null) return true
	if ( pObj.value == '' && pTipo != 'validmail' && pTipo != 'validdate') {
		alert(pControl + " es requerido...");
		pObj.focus();
		return false;
	} else {
		//Ahora debo corroborar que el dato sea del tipo que se especifica en el parametro pTipo
		switch ( pTipo ) {
			case "mail":
				//Corroborar que el dato sea una direccion de email valida
				if ( pObj.value.indexOf ('@', 0) == -1 || pObj.value.indexOf ('.' , 0) == -1 ) {
					alert(pControl + " no es una dirección de e-mail válida...");
					pObj.focus();
					return false ;
				} else {
					return true ;
				}
				break;
			case "validmail":
				if (pObj.value == '') return true;
				if ( pObj.value.indexOf ('@', 0) == -1 || pObj.value.indexOf ('.' , 0) == -1 ) {
					alert(pControl + " no es una dirección de e-mail válida...");
					pObj.focus();
					return false ;
				} else {
					return true ;
				}
				break;			
			case 'date':
			case 'validdate':
				if (pObj.value == '') return true;
			case 'date':
				if (!isDate(pObj.value)) {
					pObj.focus();
					return false;
				}
				return true;
				break;
			case "int":
				break;
			case "url":
				if(!isValidURL(pObj.value)){
					alert(pControl + " no es una url válida...");
					pObj.focus();
					return false;
				}
				return true;
				break;
		}
		return true;
	}
}

//Funcion que inicializa el objeto ajax
function initAjax(){
	var ajax=false;

	/*@cc_on @*/
	
	/*@if (@_jscript_version >= 5)
	
	try {
	
	ajax = new ActiveXObject("Msxml2.XMLHTTP");
	
	} catch (e) {
	
		try {
	
	ajax = new ActiveXObject("Microsoft.XMLHTTP");
	
	} catch (E) {
	
	ajax = false;
	
	}
	
	}
	
	@end @*/
	
	if (!ajax && typeof XMLHttpRequest!='undefined') ajax = new XMLHttpRequest();
	return ajax;
}

//Funcion que coloca en el divId el resultado del archivo url
function TGAjax ( url , divId , sync, method) {

	var ajax = initAjax() ;    
	
	if (typeof sync == 'undefined') sync = false;

	if (typeof method == 'undefined') method = 'GET';
	options =  { asynchronous: !sync } ;
	AppObj.Ajax.updaterAjax(url,divId,options);
}

function isValidURL(url){
    var RegExp = /^(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$/;
    if(RegExp.test(url)){
        return true;
    }else{
        return false;
    }
}

function showWaitAjax(intHeight){
	var strHtml = '<div class="waitingimage"  align="center" style="width:100%;min-height:' + intHeight + 'px"><img border="0" src="/vistas/images/wait.gif"><div class="waitingimagetext">Cargando...</div></div>';
	return strHtml
}

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }
		return string;
    }
}

function goToPilot(obj){
	var body=document.getElementsByTagName("body");
	var frm=document.createElement('form');
	frm.id="frm_send";
	frm.name="frm_send";		
	frm.action='/modules/pilots/index.php' ;
	frm.method="post";
	
	var op=document.createElement('input');
	op.type="hidden";
	op.id="op";
	op.name="op";
	op.value="driver";
	frm.appendChild(op);		
	
	var idAuto=document.createElement('input');
	idAuto.type="hidden";
	idAuto.id="idAuto";
	idAuto.name="idAuto";
	idAuto.value=obj.idAuto;
	frm.appendChild(idAuto);
	
	var idDriver=document.createElement('input');
	idDriver.type="hidden";
	idDriver.id="idDriver";
	idDriver.name="idDriver";
	idDriver.value=obj.idDriver;
	frm.appendChild(idDriver);		
	
	var idCategoria=document.createElement('input');
	idCategoria.type="hidden";
	idCategoria.id="idCategoria";
	idCategoria.name="idCategoria";
	idCategoria.value=obj.idCategoria;
	frm.appendChild(idCategoria);					
	
	var idCalendario=document.createElement('input');
	idCalendario.type="hidden";
	idCalendario.id="idCalendario";
	idCalendario.name="idCalendario";
	idCalendario.value=obj.idCalendario;
	frm.appendChild(idCalendario);		
	
	body[0].appendChild(frm);
	
	frm.submit();
	Element.remove(frm);	
}

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

function goToPhotoPage(intPage) {
	AppObj.Ajax.updaterAjax('/modules/gallery/ajax_photo.php?idgallery=' + $V('hdn_expanded_gallery') + '&page=' + intPage,'div_gallery_photos',{onComplete  : function() {	myLightbox.updateImageList(); }});
	Effect.ScrollTo('div_expanded_gallery');
}

function goToGallerResultPage(intPage) {
	AppObj.Ajax.updaterAjax('/modules/gallery/ajax_search.php?page=' + intPage + '&objoptions=' + $V('hdn_options'),'div_gallery_search_results');
}
function goGalleries (intSection) {
	var strOptions = Object.toJSON({intSection: intSection,strSearch: ''});		
	AppObj.Ajax.updaterAjax('/modules/gallery/ajax_search.php?objoptions=' + strOptions ,'div_gallery_search_results');
}

function searchGallery() {
	$('hdn_options').value = Object.toJSON({intSection: $V('select_section'),strSearch: $V('text_search_for')});
	AppObj.Ajax.updaterAjax('/modules/gallery/ajax_search.php?objoptions=' + $V('hdn_options'),'div_gallery_search_results');

}

function searchNews() {
	createCookie('navigation','Novedades') ;
	$('form_search').submit();
}

function isEnterKey(e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	return (keycode == 13);
}

function expandGallery (intIdGallery, strSitioRequest) {
	if ($('div_expanded_gallery')!=null) {
		AppObj.Ajax.updaterAjax('/modules/gallery/expand_gallery.php?idgallery='+intIdGallery+'&strSitioRequest='+strSitioRequest,'div_expanded_gallery',{onComplete  : function() {	myLightbox.updateImageList(); }});
		if (document.viewport.getScrollOffsets().top>0) { Effect.ScrollTo('div_expanded_gallery'); }
	} else {
		document.location.href = '/modules/gallery/?idgallerie=' + intIdGallery;
	}
}

function showGaleries(strObject, strSitioRequest) {
	var arr = eval(strObject);
	if (arr.length>0) {
		expandGallery (arr[0], strSitioRequest); 
	}
	if (arr.length>1) {
		AppObj.Ajax.updaterAjax('/modules/gallery/ajax_more_galleries.php?searchfor=' + Object.toJSON(arr),'div_gallery_search_results');
	}
}

function NavTopTen(strUrl) {
	var intAle = Math.round(Math.random()*10000);
	strUrl = strUrl.replace( new RegExp("[?]","g"),"PREG");
	strUrl = strUrl.replace( new RegExp("[&]","g"),"AMP");
	strUrl = '/modules/ws/geturlajax.php?wsUrl='+strUrl;
	AppObj.Ajax.updaterAjax(strUrl+'?ale='+intAle,'div_TopTenMain');
}

function NavPlayOffLeft(strUrl) {
	var intAle = Math.round(Math.random()*10000);
	strUrl = strUrl.replace( new RegExp("[?]","g"),"PREG");
	strUrl = strUrl.replace( new RegExp("[&]","g"),"AMP");
	strUrl = '/modules/ws/geturlajax.php?wsUrl='+strUrl;
	AppObj.Ajax.updaterAjax(strUrl+'?ale='+intAle,'div_PlayOffLeft');
}

function showFullChampionship(intCat, strSitioRequest, strURLWebsercices) {
	var aleatorio = Math.round(Math.random()*10000);
	if ($('hdn_ppcev_data')!=null) { // In ppcev
		strUrlEmbebida = 'http://'+strURLWebsercices+'/upload/htmls/'+strSitioRequest+'/campeonato_2009_'+intCat+'.htm?ale='+aleatorio;
		strUrlEmbebida = strUrlEmbebida.replace( new RegExp("[?]","g"),"PREG");
		strUrlEmbebida = strUrlEmbebida.replace( new RegExp("[&]","g"),"AMP");
		var strUrl = '/modules/ws/geturlajax.php?wsUrl='+strUrlEmbebida;
		AppObj.Ajax.updaterAjax(strUrl,'div_ppcev_content');
	} else {
		window.location.href='/modules/championship/index.php?cat='+intCat;
	}
}

function showFullPlayOff(intCat, strSitioRequest, strURLWebsercices) {
	var aleatorio = Math.round(Math.random()*10000);
	if ($('hdn_ppcev_data')!=null) { // In ppcev
		strUrlEmbebida = 'http://'+strURLWebsercices+'/upload/htmls/'+strSitioRequest+'/playoff_center_'+intCat+'.htm?ale='+aleatorio;
		strUrlEmbebida = strUrlEmbebida.replace( new RegExp("[?]","g"),"PREG");
		strUrlEmbebida = strUrlEmbebida.replace( new RegExp("[&]","g"),"AMP");
		var strUrl = '/modules/ws/geturlajax.php?wsUrl='+strUrlEmbebida;
		AppObj.Ajax.updaterAjax(strUrl,'div_ppcev_content');
	} else {
		window.location.href='/modules/playoff/index.php?cat='+intCat;
	}
}

function ChangeIconCat(intIdCat, strModule) {
	var strIcon = '';
	switch(intIdCat) {
		case 1:
			strIcon = 'tc';
			break;
		case 2:
			strIcon = 'tcp';
			break;
		case 8:
			strIcon = 'tcm';
			break;
		case 9:
			strIcon = 'tcpm';
			break;
	}
	document.getElementById('imgCatSeleccionada_'+strModule).src ='/vistas/images/seccion_'+strIcon+'.jpg';
}

function imgShow(url,title) {
	if (typeof title == 'undefined') title = '';
	var div = new Element('div', { 'style': 'display:none' });
	var a = new Element('a', { 'rel': 'lightbox[roadtrip]', href: url, 'title':title });
	div.insert(a);
	$('box').insert(div);
	myLightbox.start(a);
	Element.remove(div);
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("El formato de la fecha formato deber&iacute;a ser: dd/mm/aaaa")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Por favor ingrese un mes v&aacute;lido")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || day > daysInMonth[month]){
		alert("Por favor ingrese un d&iacute;a v&aacute;lido")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Por favor ingrese un año de 4 d&iacute;gitos entre "+minYear+" y "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Por favor ingrese una fecha v&aacute;lida")
		return false
	}
return true
}
