var map      = null;
var geocoder = null;
var jsonMapa;
 
// inicializar baseIcon
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);

window.addEvent('domready', function() {
    if (GBrowserIsCompatible()){
        map = new GMap2(document.getElementById("mapa"));
        map.setCenter(new GLatLng(20.0,-35.0), 2);
        map.setUIToDefault();
        geocoder = new GClientGeocoder();
    }
    cargarMapa();
    cargarMinaMin('divminamin',30000,0);
    cargarComentarios('ultimosComentarios',30000,0);
   
    obj = new Swiff('http://www.tvazteca.com/laacademia/fla/principalAcademia_4.swf', {
		id: 'flashPrincipal',
		width: 950,
		height: 363,
		params: {
		 	wmode: 'transparent',
		 	allowfullscreen: 'true',
		 	menu:'false',
		 	quality:'high',
	 	 	allowScriptAccess:'always'
			},
			vars: {
				archivoXML:'http://www.tvazteca.com/laacademia/fla/xml/alumnos.xml'
		},
		container: $('flashPrincipal')
	});
});


function cargarMinaMin(idDiv,time,idUltNo){
    	var request = new Request.JSON({
		url: '/laacademia/comentariosazt/220031,220166,28636/5/all/1/0/0/'+idUltNo,
        onRequest: function(){
            if(!$('ultimoCom'+idDiv)){
                alert('No existe');
            }
        },
		onComplete: function(jsonObj){         
            if(!jsonObj){        //Validacion de json 
                setTimeout("cargarMinaMin('"+idDiv+"',"+time+","+idUltNo+")",time);    
                return;
            }
            if(jsonObj.nElementos==0){ //Validacion de elementos
                setTimeout("cargarMinaMin('"+idDiv+"',"+time+","+idUltNo+")",time);    
                return;
            }
            Naux = jsonObj.nElementos;
            if( $('ultimoCom'+idDiv).value == jsonObj.comTVA[0]['id']){ //Validacion de elemntos nuevos.
                setTimeout("cargarMinaMin('"+idDiv+"',"+time+","+idUltNo+")",time);    
                return;
            }
            //$(idDiv).fade(0);           
            $('ultimoCom'+idDiv).value = jsonObj.comTVA[0]['id'];
            var htmlMM = '';
            var x;
            var img;
            for(x=0;x<Naux;x++){
                elemento = jsonObj.comTVA[x];
                img = imagenesCom(elemento.sexo,elemento.avatar);
                url = urlCom(elemento.url,elemento.tp);
                htmlMM +='<div class="entidad ">' +
    			            '<div class="entidad">' +
    				            '<p class="fontSize14 fontBold colorNaranja margin-B3">'+elemento.nombre+'</p>' +
    				        '</div>' +
    				        '<div class="avatarbox margin-RB10 fleft">' +
        				        '<div class="avatarpic borderRadius5 fleft"><a class="fontSize12 colorGrisObscuro margin-B2 block" href="'+url+'"><img src="'+img +'"/></a></div>' +
        					    '<div class="avatarshape fleft">' +
            					        '<img alt="" src="http://www.statictvazteca.com/academia2009/images/avatarshape.gif"/>' +
        					    '</div>' +
    				        '</div>' +
    				            '<a class="fontSize12 colorGrisObscuro margin-B2 block" href="'+url+'">'+cut_string(elemento.mensaje,20)+'</a>' +
    				            '<p class="fontSize12 colorGrisMedio">'+elemento.fecha+'&nbsp;'+elemento.hora+'</p>' +
  			             '</div>'; 
            }
            $(idDiv).innerHTML  =  htmlMM + $(idDiv).innerHTML;           
            setTimeout("cargarMinaMin('"+idDiv+"',"+time+","+$('ultimoCom'+idDiv).value+")",time);
    	},
        onSuccess: function(){
            //setTimeout("$('"+idDiv+"').fade(1)",1500);
             
        },
        onFailure: function(xhr){
            //alert(xhr);
        }
	}).send(); 
}

function cargarMapa(idDiv){
  	var request = new Request.JSON({
        url: '/laacademia/comentariosazt/all/50/all/2/1/1/0',
		onComplete: function(jsonObj){
            if(!jsonObj){        //Validacion de json 
                setTimeout("cargarMapa()",10000);    
                return;
            }
            if(jsonObj.nElementos==0){ //Validacion de elementos
                setTimeout("cargarMapa()",10000);     
                return;
            }
            Naux = jsonObj.nElementos;    
            itemxPag = 10;
            NumPag = Naux / itemxPag;        
            jsonMapa = jsonObj;
            auxTim = 0;
            for(var it=0;it<NumPag;it++){
                auxTim = 2000*it;
                setTimeout("MostrarComentMap("+it+")",auxTim); 
            }
            
             setTimeout("scrollMap()", auxTim+5000);
        }
	    }).send();     
}

function cargarComentarios(idDiv,time,idUltNo){
  	var request = new Request.JSON({
        url: '/laacademia/comentariosazt/all/5/all/2/0/1/'+idUltNo,
        onRequest: function(){
            if(!$('ultimoCom'+idDiv)){
                alert('No existe');
            }
        },
		onComplete: function(jsonObj){         
            if(!jsonObj){        //Validacion de json 
                setTimeout("cargarComentarios('"+idDiv+"',"+time+","+idUltNo+")",time);    
                return;
            }
            if(jsonObj.nElementos==0){ //Validacion de elementos
                setTimeout("cargarComentarios('"+idDiv+"',"+time+","+idUltNo+")",time);    
                return;
            }
            Naux = jsonObj.nElementos;
            if( $('ultimoCom'+idDiv).value == jsonObj.comTVA[0]['id']){ //Validacion de elemntos nuevos.
                setTimeout("cargarComentarios('"+idDiv+"',"+time+","+idUltNo+")",time);    
                return;
            }
                      
            $('ultimoCom'+idDiv).value = jsonObj.comTVA[0]['id'];
            var htmlUC = '';
            var x;
            var img;
            for(x=0;x<Naux;x++){
                elemento = jsonObj.comTVA[x];
                img    = imagenesCom(elemento.sexo,elemento.avatar);
                urle    = urlCom(elemento.url,elemento.tp);
                Opcion = textCom(elemento.url,elemento.tp);
                $aux = '';
                if(idUltNo!=0){
                    $aux = 'id="'+elemento.url+elemento.tp+'" style="display:none;"';
                }else{
                    $(idDiv).fade(0);
                }
                htmlUC += '<div class="entidad" '+$aux+'>' + 
                            '<div class="entidad maincom">' +
                                '<div class="col306">' +
                                    '<div class="col306 comtop block">' +
                                        '<img alt="" src="http://www.statictvazteca.com/academia2009/images/commentsup.jpg"/>' +
                                    '</div>' +
                                    '<div class="commid">' +
                                        '<a class="fontSize12 colorGrisObscuro margin-B2 block" href="'+urle+'">'+cut_string(elemento.mensaje,25)+'</a>' +
                                    '</div>' +
                                    '<div class="col306 combot">' +
                                        '<img alt="" src="http://www.statictvazteca.com/academia2009/images/commentsbottom.jpg"/>' +
                                    '</div>' +
                                '</div>' +
                            '</div>' +
                            '<div class="entidad padding-T5 padding-B5">' +
                                '<div class="col-4">' +
                                    '<p class="fleft fontSize11 colorGrisMedio margin-L5"></p>' +
                                    '<a class="fleft fontSize11 colorAmarillo fontItalic fontBold" href="'+urle+'"> '+Opcion+'&nbsp;</a>'+
                                '</div>'+
                                '<div class="col-4 fright">' +
                	                '<a href="'+urle+'">' +
                                        '<img class="fright" src="'+img+'" />' +
                                    '</a>' +
                                    '<a class="fontSize11 colorAmarillo fontItalic fontBold" href="'+urle+'">'+elemento.nombre+'</a>' +
                                    '<p class="fontSize11 colorGrisMedio">'+elemento.edo+'</p>' +
                                '</div>' +
                            '</div>'+
                        '</div>';

            }
            $(idDiv).innerHTML  =  htmlUC+$(idDiv).innerHTML;
            if(idUltNo!=0){
                setTimeout("$('"+elemento.url+elemento.tp+"').style.display = '';",1500);
                setTimeout("$('"+elemento.url+elemento.tp+"').fade(1);",1500);
            } else{
                setTimeout("$('"+idDiv+"').fade(1)",1500);
            }
            setTimeout("cargarComentarios('"+idDiv+"',"+time+","+$('ultimoCom'+idDiv).value+")",time);
            
    	},

        onSuccess: function(){
          //  setTimeout("$('"+idDiv+"').fade(1)",1500);
        },
        onFailure: function(xhr){
            //alert(xhr);
        }
	}).send(); 
}

function imagenesCom(sexo,avatar){
    if(avatar==''){ avatar = '01'};
    if(sexo == 1){
        img = 'http://www.statictvazteca.com/navegacion/barra/images/male/'+avatar+'.jpg"';
    }else{
        img = 'http://www.statictvazteca.com/navegacion/barra/images/female/'+avatar+'.jpg"';                            
    }
    if(avatar.length > 3){
        img = avatar;
    }
    return img;   
}

function textCom(idForo, tipCom){
    var text =''; 
     url = '/laacademia/iranota/'+idForo+'/'+tipCom;
    if (tipCom == 1) {
        switch (idForo) {
            case '1001':
                text = 'En el Concierto';
                break;
            case '1002':
                text = 'En el Videochat';
                break;
            case '1003':
                text = 'En la Transmision';
                break;
            case '1004':
                text = 'En el Infiltrado';
                break;
            default :
                text = 'Descubre en que Perfil'
        }
    }else{
            text = 'Descubre en que Nota'
    }
    return text;   
}


function relative_time($fecha){
    
    
}

function urlCom(idForo, tipCom){
    url = '/laacademia/iranota/'+idForo+'/'+tipCom;
    if (tipCom == 1 || tipCom == '1') {
        switch (idForo) {
            case '1001':
                url = '/laacademia/concierto';
                break;
            case '1002':
                url = '/laacademia/videochat';
                break;
            case '1003':
                url = '/laacademia/transmision';
                break;
            case '1004':
                url = '/laacademia/infiltrado';
                break;
        }
    }
    return url;
}

function cut_string(string, charlimit)
{
    Palabras = string.split(" "); 
    var palab ='';
    aux = 0;
    var auxiliar  = Palabras;
 
    fun = 0;
   /*for(item in Palabras){
         fun = item * 1; 
        if (fun > 0) {
            if (item == charlimit) {
                palab += '... ';
                return palab;
            }else {
                palab += Palabras[item] + ' ';
            }
        }
   
    }*/
   
   
   
    return string;
}



//---------------------------------//
//           GEOCODER
//---------------------------------//
function showAddress(address, zoom, elemento) {
	if (geocoder) {
    	geocoder.getLatLng(address,
      		function(point) {
        		if (!point) {
        			//alert(address + " not found");
        		} else {
                    var letteredIcon = new GIcon(baseIcon);
                    letteredIcon.image = "http://www.tvazteca.com/iconos/markerTVA.png";
                    markerOptions = { icon:letteredIcon };
        			var marker = new GMarker(point,markerOptions);
        			map.addOverlay(marker);
                    msj = '';
                    msj = elemento.mensaje;
                    GEvent.addListener(marker, "click", function() {

                    img = imagenesCom(elemento.sexo,elemento.avatar);
                    img = '<img class="fright" src="'+img+'" alt="Mi Perfil"/>';
                    url = urlCom(elemento.url,elemento.tp);
                    html = '<div class="laacademia-notas-rowleft">' +
                       	       '<div class="laacademia-notas-divportrait"> '+ img +'</div>' +
                               '<div class="laacademia-notas-divdata">' +
                                   '<span class="laacademia-notas-portname">'+elemento.nombre+'</span>'+
                                   '<br/><span class="laacademia-notas-spandate">'+elemento.fecha+'</span>&nbsp;<span class="laacademia-notas-hour">'+elemento.hora+'</span>' +
                               '</div>' +
                           '</div>' +
                           '<div class="laacademiamensaje">' +
                               cut_string(elemento.mensaje,20)+ '<a href="'+url+'" target="_black"> mas.</a>' +
                           '</div>';
                        marker.openInfoWindowHtml(html);
                    });
           		}
           	}
    	);
	    }
}

function MostrarComentMap(pag){
    var item = 10;
    var Ini = pag * item;
    var Fin = Ini + item;
    var url ='';
    for(var x=Ini;x<Fin;x++){
            html2 = '';
            elemento = jsonMapa.comTVA[x];
             if(elemento.edo!=null && elemento.edo!='' && elemento.edo!='null'){
                showAddress(elemento.edo,3, elemento);
                img = imagenesCom(elemento.sexo,elemento.avatar);
                url = urlCom(elemento.url,elemento.tp);
                url = "javascript: showAddressL('"+elemento.edo+"',10,"+x+")";
                
                img = '<img class="fright margin-R10" src="'+img+'" alt="'+elemento.nombre+'"/>';
                avat = elemento.avatar;
                if(avat.length > 3){
                    img = '<img class="fright margin-R10" src="'+elemento.avatar+'" alt="Mi Perfil"/>';
                } 
                html2 ='<div class="mapdivthumb"> ' +
                           '<a href="'+url+'">'+img+'</a>' +
                       '</div>';           
                $('scontM1').innerHTML = $('scontM1').innerHTML + html2;
            }  
    }
}
function votaPulso(cMd5,cons,Rs){
    var Resp1 = 0;
    var Resp2 = 0;
	var request = new Request({
		url: '/encuestas/resultadosPulso.php',
        method: 'POST',
		onSuccess: function(texto){
            if(texto == "0" || texto == 0){
              //alert('El día de hoy ya voto en esta encuesta');
            }else{
                Resp1 = $(cons+'_'+Rs).value * 1; 
                $(cons+'_'+Rs+'_Num').innerHTML = Resp1 + 1;
                $(cons+'_1').value = $(cons+'_1_Num').innerHTML; 
                $(cons+'_2').value = $(cons+'_2_Num').innerHTML;
                Resp1 = $(cons+'_1').value * 1; 
                Resp2 = $(cons+'_2').value * 1;
                Porc1 = Math.round(100 * (Resp1 / (Resp1 + Resp2)));   
                Porc2 = 100 - Porc1;
                $(cons+'_1_Por').innerHTML = Porc1;
                $(cons+'_2_Por').innerHTML = Porc2;
                $(cons+'_1_Barr').style.width = Porc1+'%';
                $(cons+'_2_Barr').style.width = Porc2+'%'; 
            }           
    	},
        onFailure: function(){
            //alert('Fallo');
        }
	}).post({'resp':cMd5});
}


function scrollMap(){
// SCROLL ----------------------------------------------------------	
	var scrollers = $(document.body).getElements('div[id*=scontM]');
	scrollers.each(function(item,index){
		var childs = item.getChildren('div[class*=mapdivthumb]');
        var setWidth = childs.length * 59;
		var newScroll = new Fx.Scroll('wrapM1', {
			duration: 6000,
			wait: true
		});
		$('scontM1').setStyle('width',setWidth);
		$('leftM1').addEvent('mouseover',function(){
			newScroll.toLeft();
		});		

		$('leftM1').addEvent('mouseout',function(){
			newScroll.cancel();
		});

		$('rightM1').addEvent('mouseover',function(){
			newScroll.toRight();
		});
        
		$('rightM1').addEvent('mouseout',function(){
			newScroll.cancel();
		});

	});
// SCROLL ----------------------------------------------------------
} 

function relative_time(time_value) {
    var values = time_value.split(" ");
    time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    delta = delta + (relative_to.getTimezoneOffset() * 60);
    
    if (delta < 60) {
        return 'hace menos de un min';
    } else if(delta < 120) {
        return 'hace un min';
    } else if(delta < (60*60)) {
        return 'hace ' + (parseInt(delta / 60)).toString() + ' min';
    } else if(delta < (120*60)) {
        return 'hace una hora';
    } else if(delta < (24*60*60)) {
        return 'hace ' + (parseInt(delta / 3600)).toString() + ' horas';
    } else if(delta < (48*60*60)) {
        return 'hace 1 dia';
    } else {
        return 'hace ' + (parseInt(delta / 86400)).toString() + ' dias';
    }
}
 
 
//---------------------------------//
//           GEOCODER
//---------------------------------//
function showAddressL(address, zoom, idElemento) {
	if (geocoder) {
    	geocoder.getLatLng(address,
      		function(point) {
        		if (!point) {
        			alert(address + " not found");
        		} else {
                    elemento = jsonMapa.comTVA[idElemento];
                    var letteredIcon = new GIcon(baseIcon);
                    letteredIcon.image = "http://www.tvazteca.com/iconos/markerTVA.png";
                    markerOptions = { icon:letteredIcon };
        			var marker = new GMarker(point,markerOptions);
        			map.addOverlay(marker);
                    msj = '';
                    msj = elemento.mensaje;
                    img = imagenesCom(elemento.sexo,elemento.avatar);
                    img = '<img class="fright" src="'+img+'" alt="Mi Perfil"/>';
                    url = urlCom(elemento.url,elemento.tp);
                    html = '<div class="laacademia-notas-rowleft">' +
                       	       '<div class="laacademia-notas-divportrait"> '+ img +'</div>' +
                               '<div class="laacademia-notas-divdata">' +
                                   '<span class="laacademia-notas-portname">'+elemento.nombre+'</span>'+
                                   '<br/><span class="laacademia-notas-spandate">'+elemento.fecha+'</span>&nbsp;<span class="laacademia-notas-hour">'+elemento.hora+'</span>' +
                               '</div>' +
                           '</div>' +
                           '<div class="laacademiamensaje">' +
                               cut_string(elemento.mensaje,20)+ '<a href="'+url+'" target="_black"> mas.</a>' +
                           '</div>';
                        marker.openInfoWindowHtml(html);
                    
                    
           		}
           	}
    	);
	    }
}