var compEncId=0;


function OddsBetType(BetTypeChg,BetTypeDet,EventoIdU){

    SetOddsBetType(BetTypeChg);

    document.location.hash=BetTypeChg+'-'+BetTypeDet+'-'+EventoIdU;
    currentAnchor=document.location.hash;
    // alert(page)
    if(page=='evento'){
        xajax_OddsBetTypeMax(BetTypeChg,EventoIdU,compEncId);
    }
    else if(page=='compare'){
        xajax_OddsBetTypeCompare(BetTypeChg,MatchupId);
        xajax_OddsBetInfoLimp();

    }
    else if(page=='tendencia'){
        casasel=document.getElementById("selcasa");
        sel=casasel.options[casasel.selectedIndex];
        if(sel.value!='-1'){
            casasel=sel.value;
        }else{
            casasel='';
        }
        xajax_OddsBetTypeCompare(BetTypeChg,MatchupId);
        xajax_OddsTendencia(MatchupId, BetType,Periado,casasel,EventoId);

    }else if(page=='info'){
        xajax_OddsBetTypeCompare(BetTypeChg,MatchupId);
    }else if(page=='foro'){
        //responder_pronosticar(currentMatch,idtipo,currentTicket);

        responder_pronosticar(currentMatch,BetTypeChg,currentTicket,EventoIdU);
         
    }
}



function OddsmatchupType(varBetType,varMatchup,varEventoID){
	if(page!='foro'){
    SetOddsBetType(varBetType);
    SetEventId(varEventoID);
    alphaOff('matchsdiv-'+varEventoID)
    compEncId=varMatchup;
    xajax_OddsmatchupType(BetType,varMatchup,EventoId)
	}else{
		 responder_pronosticar(varMatchup,varBetType,currentTicket,varEventoID);
	}
}



function OddsFormat(Format){
	
    //alert(Format + ' ' + BetType + ' ' + EventoId);
    if(page=='evento'){
        xajax_OddsFormat(Format,BetType,EventoId);
    }
    else if(page=='compare'){
        xajax_OddsOddsFormatCompare(Format,BetType,EventoId);
    }
}

function refrescar(){
    if(page=='evento'){
        alphaOff("matchsdiv");
        xajax_RefrescarMaxOdds(EventoId,BetType);
    }
    else if(page=='compare'){
        alphaOff("MainCompare");
        xajax_RefrescarCompareOdds(MatchupId,BetType);
    }
    else if(page=='tendencia'){
        alphaOff("MainCompare");
        casasel=document.getElementById("selcasa");
        sel=casasel.options[casasel.selectedIndex];

        if(sel.value!='-1'){
            casasel=sel.value;
        }else{
            casasel='';

        }
        xajax_OddsTendencia(MatchupId, BetType,Periado,casasel,EventoId);
    }
}
function showTip(btpid,idev)
{
    ele=document.getElementById('bet_'+btpid+'_tip'+idev);
    ele.style.top=(document.getElementById('bet_type_'+btpid+'_ev'+idev).offsetTop-25)+'px';

    ele.style.visibility='visible';
}
function SetOddsBetType(VarBetType){
    BetType=VarBetType;
}
function SetEventId(VarEventId){
    EventoId=VarEventId;
}
function SetPage(VarPage){
    page=VarPage;
}
/**
 *Control bet borrowed functions
 */
function AddTicket(IdEnc, Select,Price)
{
    //alert(IdEnc+ " " + Select + " " + Price);
	if(page!='foro')
    	xajax_AddTicket(IdEnc,Select,Price,0);
    else
    	xajax_AddTicket(IdEnc,Select,Price,1);
}
function DelTicket(IdEnc)
{
    xajax_DelTicket(IdEnc);
}
function calculate(win, i, maxgain)
{
    var Import ;
    var Price ;
    var Winner;
    var result;
    var WinnerNeto;

    estilo='';

    if(win=='IN'){
        Import = document.getElementById('importe'+i);
        Price = document.getElementById('price'+i);
        Winner = document.getElementById('win'+i);
        WinnerNeto = document.getElementById('winNeto'+i);
        

        Total=Import.value*Price.value;
        result=calRound(Total) ;
        if(result>maxgain){
            estilo=' style="color:red;"'
        }
        TotalNeto= Total-Import.value;
        resultNeto=calRound(TotalNeto);
    }

    if(win=='ALL'){

        Import = document.getElementById('importe'+i);
        Price = document.getElementById('pricetotal'+i);
        Winner = document.getElementById('win'+i);
        WinnerNeto = document.getElementById('winNeto'+i);   

        Total=Import.value*Price.value;
        result=calRound(Total) ;


        TotalNeto= Total-Import.value;
        resultNeto=calRound(TotalNeto);

    }
    if(win=='CALL'){
        var PriceTotal=1;
        for (j=1;j<=i;j++)
        {
            var price = document.getElementById('price'+j);
            PriceTotal=PriceTotal*price.value;
        }


        Import = document.getElementById('importe'+i);
        Winner = document.getElementById('win'+i);
        WinnerNeto = document.getElementById('winNeto'+i);   
        var ptotal = document.getElementById('ptotal'+i);


        Total=Import.value*calRound(PriceTotal);
        result=calRound(Total);  
        TotalNeto= Total-Import.value;
        resultNeto=calRound(TotalNeto);

        ptotal.innerHTML='<input type="hidden" name="pricetotal'+i+'" id="pricetotal'+i+'" size="8" value="'+calRound(PriceTotal)+'" style="font-size: 10px">Cuota Total:</font> <b>'+calRound(PriceTotal)+'</b>';

    }

    Winner.innerHTML='<font color="#808000" size="1" face="Verdana">Retorno:</font> <b'+estilo+'>'+result+'</b>';
    WinnerNeto.innerHTML='<font color="#808000" size="1" face="Verdana">Ganancia Neta:</font> <b>'+resultNeto+'</b>'; 
/*if(result>maxgain){
        document.getElementById('maxPuntosGain').innerHTML=''+Math.floor(maxgain/Price.value);
        $("#maxgainDiag").dialog({
            modal:true,
            autoOpen: false,
            buttons: {
                "Aceptar": function() {
                    $(this).dialog("close");
                }
            }

        });
        $("#maxgainDiag").dialog('open');
        document.getElementById('importe'+i).focus();
    }*/
}
function calRound(number){

    var original=parseFloat(number);
    var result=Math.round(original*100)/100;
    return result;

}
function simple_values(_name,maxgain,team){
    var _total = _name.slice(7);
    var spread = null;
    var over_under = null;
	var cantpal = 0;
    //alert(cuota);
    if(document.getElementById('price'+_total) != null)
        _cuotas = parseFloat(document.getElementById('price'+_total).value);
    if(document.getElementById('importe'+_total) != null)
        _importe = document.getElementById('importe'+_total).value;
    if(document.getElementById('comentario'+_total) != null){
        _coment = document.getElementById('comentario'+_total).value;
		cantpal = _coment.length;
		//_coment = _coment.trim();
		}
    if(document.getElementById('spread'+_total) != null)
        spread =parseFloat(document.getElementById('spread'+_total).value);
    if(document.getElementById('over_under'+_total)!=null)
        over_under = parseFloat(document.getElementById('over_under'+_total).value);
 
    var result=_cuotas*_importe;
    //alert(_importe+"@"+_cuotas)

    
    //Para Espacios en Blanco en Medio (no incluido) Gab
    //_coment = _coment.replace(/\s{8,}/g, " ");

   
    if(cantpal>0 && cantpal<200){
        //alert(cantpal)
        MsgUsers("Todavía te faltan un minimo de "+(200-cantpal)+" caracteres para completar el comentario.",true);
        return false;
    }
    if(result>maxgain){
        //document.getElementById('maxPuntosGain'+_total).innerHTML=''+Math.floor(maxgain/_cuotas);
        document.getElementById("maxgainDiag"+_total).innerHTML='El máximo de puntos que puede apostar a esta cuota es de '+Math.floor(maxgain/_cuotas);
        //document.getElementById("maxgainDiag"+_total).innerHTML='El máximo de puntos que puede apostar a esta cuota es de '+Math.floor(maxgain/_cuotas);
        //alert('El máximo de puntos que puede apostar a esta cuota es de '+Math.floor(maxgain/_cuotas))
        //alert("#maxgainDiag"+_total);
        $("#maxgainDiag"+_total).dialog({
            modal:true,
            autoOpen: true,
            buttons: {
                "Aceptar": function() {
                    $(this).dialog("close");
                }
            }

        });
        //$("#maxgainDiag"+_total).dialog('open');
        document.getElementById('importe'+_total).focus();
        return false;
    }
    if(!is_int(_importe)){
        MsgUsers("El importe debe ser un numero entero.",true);
        return false;
    }
    if(isNaN(_cuotas) || isNaN(_importe))
    {
        MsgUsers("El importe debe ser un numero entero.",true);
        return false;
    }

    if(spread != null)
        if(isNaN(spread)){
            MsgUsers("La ventaja debe ser numerica",true);
            return false;
        }

    if(over_under != null)
        if(isNaN(over_under)){
            MsgUsers("El total debe ser numerico",true);
            return false;
        }

    if ( _importe <= 0 || _importe == false ) {
      	
        MsgUsers("El importe debe ser un numero mayor que cero",true);
					
        return false;
    }
    else
    if (_cuotas <= 0) {
        MsgUsers("La cuota debe ser un numero mayor que cero",true);
        return false;
    }
    else {
        // alert(_cuotas + " "+ _importe+ " "+ _coment+ " "+ _total+ " "+ spread+ " "+ over_under);
	   
        //MsgConf(_cuotas, _importe, _coment, _total, spread, over_under);
        //alert('#'+'ConfImp_'+_name);
        //document.getElementById('ConfImp_'+_name).innerHTML=''+_importe+' puntos';
    	
    	divbody='Está seguro que desea este pronóstico?<br><br>';
        divbody+='<b>'+team+'</b> @ <b>'+_cuotas+'</b><br><b style="color:red">'+_importe+' puntos</b>';
    	document.getElementById('Conf_Agendar').innerHTML=divbody;
            //alert(document.getElementById('Conf_Agendar').innerHTML)
    	
        $('#Conf_Agendar').dialog({
            autoOpen: false,           
            modal:true,           
            buttons: {
               
                "Cancelar":function() {
                    $(this).dialog("close");
                    $(this).dialog("destroy");
                },
                "Aceptar": function() {
                    $('#'+_name).attr('disabled', 'disabled');
                    xajax_insertPronostico(_cuotas, _importe, _coment, _total, spread, over_under);
                    $(this).dialog("close");
                    $(this).dialog("destroy");
                }
            }

        });
        $('#Conf_Agendar').dialog('open');
       
        //$('#'+'Conf_'+_name).dialog('open');
    //$('#Agendar2').attr('disabled', 'disabled');
    //xajax_insertPronostico(_cuotas, _importe, _coment, _total, spread, over_under);

    }
    return false;

}
function ConfTicket(_cuotas, _importe, _coment, _total, spread, over_under){
    xajax_insertPronostico(_cuotas, _importe, _coment, _total, spread, over_under);
}
function MsgUsers(Msg,error){

    dtitle='Mensaje';
    if(error){
        Msg='<div class="ui-widget"><div class="ui-state-error ui-corner-all" style="padding: 0pt 0.7em;"><p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: 0.3em;"></span><strong>Alerta:</strong> '+Msg+'</p></div></div>';
        dtitle= 'Mensaje de Error';
    // Dialog
    }

    $('#new_prono_diag').html('<div class="Dmsgbody">'+Msg+'</div>');
    
    $('#new_prono_diag').dialog({
        autoOpen: false,
        width: 350,
        height:100,
        title:dtitle,
        modal:true,
        buttons: {
            "Aceptar": function() {
                $(this).dialog("close");
            }
        }
	
    });
    $('#new_prono_diag').dialog('open');
    /*if(page=='foro' && !error){
        turl=window.location+"";
        urlarr=turl.split("ver_foro/");
        if(urlarr[1].indexOf("/")>=0){
            urlarr=urlarr[1].split("/");
            topic=urlarr[0];
        }else{
            topic=urlarr[1];
        }
		
        this.location.href = "/modules/centroforo/index.php/foros/goLastPost/"+topic;
    }*/
    return false;

}


function MsgConf(_cuotas, _importe, _coment, _total, spread, over_under){
	
    Ticket='Valores del Tikert';
    // Dialog
			
    $('#dialogTicket').dialog({
        autoOpen: false,
        width: 300,
        buttons: {
            "Aceptar": function() {
                $(this).dialog("close");
                ConfTicket(_cuotas, _importe, _coment, _total, spread, over_under);
                VarConfTicket=true;
            },
            "Cancelar": function() {
                $(this).dialog("close");
							

            }
        }
    });
    $('#dialogTicket').dialog('option', 'title', 'Confirmacion del Pronosticos');
    $('#dialogTicket').html(Ticket);
    $('#dialogTicket').dialog('open');
    return false;

}





function sendform(url){

    if(document.getElementById('deporte').options[document.getElementById('deporte').selectedIndex].value)
        var deporte = document.getElementById('deporte').options[document.getElementById('deporte').selectedIndex].value;
	
    if(document.getElementById('pais').options[document.getElementById('pais').selectedIndex].value)
        var paises = document.getElementById('pais').options[document.getElementById('pais').selectedIndex].value;

    if(document.getElementById('evento').options[document.getElementById('evento').selectedIndex].value && document.getElementById('evento').options[document.getElementById('evento').selectedIndex].value != "0"  && document.getElementById('evento').options[document.getElementById('evento').selectedIndex].value != "-1")
        var evt = document.getElementById('evento').options[document.getElementById('evento').selectedIndex].value;

    if (deporte && deporte != "" && deporte!=0) {
        url = url + 'ligas_pronosticos+deport-' + deporte;

        if (paises && paises !="" && paises !=0) {
            url = url + '-pais-' + paises.toLowerCase();

            if (evt && evt !="" && evt!=0) {
                url = "ligas_pronosticos+" + 'id_eventos\n\
-' + evt;
            //
            }
        }
        url = url +'.html';
        window.location=url;
    }
}

function alphaOff(IdElement){
	
    document.getElementById(IdElement).style.opacity='.5';
    document.getElementById(IdElement).style.filter='alpha(opacity=50)';

	
}

function alphaOn(IdElement){
     
    document.getElementById(IdElement).style.opacity='1';
    document.getElementById(IdElement).style.filter='alpha(opacity=100)';
	
}


function imprimirTicket(){
     
    xajax_imprimirTicket();
	
}

// ************** End of odds Javascripts *********************

$(function(){
    $('#SelectLiga').change(function(){
        var ligaID = this.value;
        //xajax_setSessionID(ligaID);
        top.location = '/pronosticos/ligas_pronosticos+ligaID-'+ligaID+'.html';

    });
    /*
    $('.activbgd').click(function(){
        // window.location = '/register.php';
        xajax_joinAllLeagues();
        $(this).hide();
    });
	*/
    $('.acced').click(function(){
        window.location = '/user.php?xoops_redirect=/modules/pronosticos/ligas_pronosticos.php';
    });
	
    /*
    $('.joinAll').click(function(){
        xajax_joinAllLeagues();
        $(this).hide();
        var log = $('#logging').attr('value');
        if (log == 1){
            $('div.LigaCont ul li > img').
            attr('src', '/modules/pronosticos/images/img1B.gif').
            attr('class', 'disableAccount');
        }
    });
    */
    $('strong#userContainer > a').css('color','white');
});

function is_int(value){
    if((parseFloat(value) == parseInt(value)) && !isNaN(parseInt(value))){
        return true;
    } else {
        return false;
    }
}

    
function drawBar(val1,val2,valx,lab1,lab2,labx){

    if(val1==0 && val2==0 && valx == 0)
    {
        document.getElementById("chart_div").innerHTML="";
        return;
    }
    data = new google.visualization.DataTable();
    data.addColumn('string', 'Task');
    data.addColumn('number', lab1+'('+val1+')');
    
    data.addColumn('number', lab2+'('+val2+')');
    if(parseInt(valx)!=0){
        data.addColumn('number', labx+'('+valx+')');
        data.addRows([

            ['Pronosticos', val1,valx,val2]
            //['mengano', 15],
            //['Empate', 5]
            ]);
    }else{
        data.addRows([
            ['Pronosticos', val1,val2]

            ]);

    }
    var chart = new google.visualization.ImageBarChart(document.getElementById('chart_div'));
    chart.draw(data, {
        width: 300,
        height: 60,
        fontSize:10
    // is3D: true,
    //isStacked:true,
    // title: 'Pronosticos del encuentro'
    });
}
var loadedEncs=false;
function showUsersStats(idenc){
    //    $("#UsersStats").fadeTo('slow',0.5);
    pos=$("#statLink"+idenc).offset();
    //alert(pos.left);
    //alert(pos.top);
    $("#UsersStats").css('top',pos.top);
    $("#UsersStats").css('left',pos.left+30);

    //enableContent('UsersStats');
    if(!loadedEncs)
        $("#UsersStats").show('slow');
    else
        enableBlock('UsersStats');
    //$("#UsersStats").fadeTo('slow',1);
    if(!loadedEncs)
        loadedEncs=true;
}

function GetEncTickets(start,idenc,tipoap){
    
    if(loadedEncs)
        //$('#UsersStats').fadeTo('slow',0.5);
        disableBlock('UsersStats');
    xajax_MatchUserStats(start,idenc,tipoap);
    
}

function disableBlock(contentid){
    x=$('#'+contentid).offset().left;
    y=$('#'+contentid).offset().top;

    $('#loadimg').css('left', x+$('#'+contentid).width()/2-15);
    $('#loadimg').css('top', y+$('#'+contentid).height()/2-15);
    $('#loadimg').css('display', 'block');
    //alert(x+','+$('#'+contentid).width()/2-15)
    $('#'+contentid).fadeTo( 'slow',0.33);

}
function enableBlock(contentid){
    //$('#loadimg').fadeOut();
    $('#'+contentid).fadeTo('slow', 1);
    $('#'+contentid).removeAttr('disabled');
    $('#loadimg').css('display', 'none');
}
function closeBlock(contentid){
    $('#'+contentid).hide('slow');
    loadedEncs=false;
}
function NextMatchPag(start){
    disableBlock('NextMatchsDiv');
    xajax_getNextMatchs(start);
}

function loadPostForo(){
	
	if(page!='foro'){
		gapi.plusone.go();
		lgn_disablePopup();
		lgn_loadPopup('postPopUp');
	}else{
		alert('Su pick ha sido realizado.!!')
		window.location.reload();
		
	}
	//$('#postPopUp').css('top',f_scrollTop()+150);
}





