(function($) {
  var appL = $.mobile.appL = {
    host: 'http://pappcornbackapp.com/ws/expWS.php',
    // host: 'http://localhost/AppNacional/ws/expWS.php',
    base: 'http://pappcornbackapp.com/adminApp/',
    idTeam: 'PAT',
    data: "",
    activePage: "",
    userPosition: "",
    cargando: false,
    cargoNoticias: false,
    noticia: false,
    load: false,
    link: true,
    init: function() {
      $(document).bind('pageinit', function() {
        $('.icoReload').click(function() {
          appL.activePage = $.mobile.urlHistory.getActive().hash;
          if (!appL.cargando) {
            appL.cargando = true;
            checkData(true);
            console.log("cambiando");
          }
        });
        console.log('this init run');
        appL.activePage = $.mobile.urlHistory.getActive().hash;
        console.log(appL.activePage);
        console.log($.mobile.urlHistory);
        $('#home').on('pageshow', function() {
          if (appL.link) {
            appL.activePage = "#menu"
          };
          console.log("tac");
        });
        if (appL.activePage != "#menu" && appL.load) {
          console.log("tic");
          appL.link = false;
        }
        if (!appL.load) {
          appL.load = true;
          checkData(true);
        }
        console.log(appL.activePage);
      });
    },
    loadPosition: function() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
          appL.userPosition = position;
        });
      } else {
        console.log('errorCargandoPosition')
      }
    },
    loadJsonData: function(f) {
      $.ajax({
        type: "POST",
        url: appL.host,
        cache: true,
        data: 'code=' + appL.idTeam + '&app=nacional',
        async: true,
        crossDomain: true,
        dataType: 'json',
        success: function(data) {
          appL.data = data;
          localStorage.setItem('dataJson', JSON.stringify(appL.data));
          console.log(appL.data);
          appL.preload();
          appL.cargando = false;
          if (typeof f == "function")
            f();
        },
        error: function(xhr, testStatus, error) {
          appL.data = localStorage.getItem('dataJson');
          if (jQuery.isEmptyObject(appL.data) || !appL.data || appL.data == "") {
            alert("No se ha podido actualizar, los datos pueden estar desactualizados.");
            appL.preload();
            if (typeof f == "function")
              f();
          } else {
            alert("No inicializar por favor inicializarla con internet.");
            $.mobile.changePage("#error", {
              transition: "slideup",
              changeHash: false
            });
          }

        }
      });
    },
    preload: function() {
      appL.loadPosition();
      loadMenu();
      mostrarNoticias();
      mostrarResultados("");
      mostrarResultados("1");
      mostrarResultados("2");
      mostrarTabla("");
      mostrarTabla("1");
      mostrarTabla("2");
      mostrarCalendarios("");
      mostrarCalendarios("1");
      mostrarCalendarios("2");
      mostrarPlayers();
      mostrarMinAmin();
      mostrarLinks();
      // mostrarBracket();
      // console.log("preResul2");
      // mostrarResultados("1");
      // console.log("preResul3");
      // mostrarResultados(2);
    },
    clean: function(f) {
      $('#news').empty();
      $('.m-carousel').carousel('destroy');
      $('#sliderNews').append("\
              <div class='m-carousel m-fluid m-carousel-photos'>\
              <div id='loadNotiCC' class='m-carousel-inner'></div>\
              <div class='m-carousel-controls m-carousel-hud'>\
              <a class='m-carousel-prev' href='#' data-slide='prev'>Previous</a>\
              <a class='m-carousel-next' href='#' data-slide='next'>Next</a>\
              </div>\
              </div>\
              ");
      var fileref = document.createElement('script');
      fileref.setAttribute("type", "text/javascript");
      fileref.setAttribute("src", 'carousel.js');
    },
  };
  appL.init();

  function loadMenu() {
    $(".menuLat").empty();
    $(".menuLat").append('\
            <div class="menuLFixed">\
            <div class="slogan"></div>\
            <div class="cuadritos">\
            <a href="#noticias"><div class="icoML left">\
            <div class="icoMI icoMenu ">\
            </div>\
            <p>NOTICIAS</p>\
            </div></a>\
            <a href="#rLiga"><div class="icoML left">\
            <div class="icoMI icoRes ">\
            </div>\
            <p>RESULT.</p>\
            </div></a>\
            <a href="#tabla"><div class="icoML left last">\
            <div class="icoMI icoTab">\
            </div>\
            <p>TABLAS</p>\
            </div></a>\
            <a href="#cLiga"><div class="icoML left">\
            <div class="icoMI icoCal ">\
            </div>\
            <p>CALEND.</p>\
            </div></a>\
            <a href="#minamin"><div class="icoML left">\
            <div class="icoMI icoMin ">\
            </div>\
            <p>MIN A MIN</p>\
            </div></a>\
            <a href="#team"><div class="icoML left last">\
            <div class="icoMI icoPlan ">\
            </div>\
            <p>PLANTEL</p>\
            </div></a>\
            <a href="#redes"><div class="icoML left firts">\
            <div class="icoMI icoRed ">\
            </div>\
            <p>REDES</p>\
            </div></a>\
            <a href="https://marketplace.firefox.com/app/ligacolombiana/" target="_blank"><div class="icoML left">\
            <div class="icoMI icoEx ">\
            </div>\
            <p>LA LIGA</p>\
            </div></a>\
            <a href="#info"><div class="icoInfo centro"></div></a>\
            </div></div>');

  }
  // forse fuerza a cargar de nuevo

  function checkData(forse, f) {
    data = localStorage.getItem('dataJson');
    try {
      appL.data = JSON.parse(data);
    } catch (err) {
      appL.data = null;
    }
    if (jQuery.isEmptyObject(appL.data) || !appL.data || appL.data == "" || forse) {
      $.mobile.changePage("#home", {
        transition: "slideup",
        changeHash: false
      });
      appL.loadJsonData(function() {
        console.log(appL.activePage);
        $.mobile.changePage(appL.activePage, {
          transition: "slideup",
          changeHash: false
        });
        if (typeof f == "function")
          f();
        console.log("pass1");
      });
    } else {
      if (typeof f == "function")
        f();
      console.log("pass2");
    }

  }
  function mostrarLinks(){
      $('#urlFacebook').attr('href', appL.data.infoTeam.facebook);
    $('#urlTwitter').attr('href', appL.data.infoTeam.twitter);
    $('#urlTwitter').attr('data-widget-id', appL.data.infoTeam.codeWidget);
    $('#urlWeb').attr('href', appL.data.infoTeam.webSite);
    !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
    $('#linkFace').attr('src', appL.data.infoTeam.facebook);
    $('#linkTwitter').attr('src', appL.data.infoTeam.twitter);
    $('#linkWeb').attr('src', appL.data.infoTeam.webSite);
    $('#linkExtra').attr('src', appL.data.infoTeam.extra);   
    $('#infoTeamC').empty(); 
    $('#infoTeamC').append(appL.data.infoTeam.info); 
    
  }
  function mostrarResultados(camp) {
    var cont = true;
    $('#results' + camp).empty();
    $.each(appL.data['res' + camp], function(index, element) {
      if (cont) {
        cont = false;
        $('#localT' + camp).empty();
        $('#visT' + camp).empty();
        $('#resT' + camp + ' h1').html(element["titulo"]);
        $('#resT' + camp + ' h5').html(element["golesLocal"] + ' - ' + element["golesVisitante"]);
        $('#resT' + camp + ' h3').html(element["estadio"]);
        $('#resT' + camp + ' h4').html(element["fecha"]);
        $('#localT' + camp).append('<div class="' + element['localCode'] + ' ico"></div><h2>' + element['localName'] + '</h2>')
        $('#visT' + camp).append('<div class="' + element['visCode'] + ' ico"></div><h2>' + element['visName'] + '</h2>')
        console.log('#localT' + camp);
      } else {
        var a = element['fecha'].split("-");
        element['mes'] = a[1] - 1;
        element['dia'] = a[2];
        var mes = getMes(element['mes']);
        var dia = element['dia'];
        var text = element['frf'];
        var number = element['numero'];
        var localname = element['localName'];
        var localGol = element['golesLocal'];
        var localIco = element['localCode'];
        var visname = element['visName'];
        var visGol = element['golesVisitante'];
        var visIco = element['visCode'];
        $('#results' + camp).append("<div class='ccResult'>\
           <div class='dateRes'>\
           <div class='mes'>" + mes + "</div>\
           <div class='dia'>" + dia + "</div>\
           </div>\
           <div class='localRes'>\
           <div class='" + localIco + "M ico left'></div>\
           <p class='left'>" + localname + "</p>\
           </div>\
           <div class='resRes'>" + localGol + " - " + visGol + "</div>\
           <div class='viRes'>\
           <p class='left'>" + visname + "</p>\
           <div class='" + visIco + "M ico right'></div>\
           </div>\
           <div class='fecha'>\
           <h2>" + text + "</h2>\
           <h1>" + number + "</h1>\
           </div>\
           </div>");
      }
    });
  }

  function mostrarCalendarios(data) {
    var cont = true;
    console.log(data);
    console.log('#calProximos' + data);
    $('#cal' + data).empty();
    $('#calProximos' + data).empty();
    $.each(appL.data['cal' + data], function(index, element) {
      if (cont) {
        cont = false;
        $('#calLocal' + data).empty();
        $('#calVis' + data).empty();        
        $('#calLink' + data).attr("href", element["link"]);
        $('#calInfo' + data + ' h1').html(element["titulo"]);
        $('#calInfo' + data + ' h3').html(element["estadio"]);
        $('#calInfo' + data + ' h4').html(element["fecha"]);
        // $('#calLink1'+data).empty();
        $('#calLocal' + data).append('<div class="' + element['localCode'] + ' ico"></div><h2>' + element['localName'] + '</h2>')
        $('#calVis' + data).append('<div class="' + element['visCode'] + ' ico"></div><h2>' + element['visName'] + '</h2>')
      } else {
        var a = element['fecha'].split("-");
        element['mes'] = a[1] - 1;
        element['dia'] = a[2];
        var mes = getMes(element['mes']);
        var dia = element['dia'];
        var text = element['frf'];
        var number = element['numero'];
        var localname = element['localName'];
        var localGol = element['golesLocal'];
        var localIco = element['localCode'];
        var visname = element['visName'];
        var visGol = element['golesVisitante'];
        var visIco = element['visCode'];
        var estadio = element['estadio'];
        var hora = element['hora'];
        var ciudad = element['ciudad'];
        $('#calProximos' + data).append("<div class='ccResult'>\
       <div class='dateRes'>\
       <div class='mes'>" + mes + "</div>\
       <div class='dia'>" + dia + "</div>\
       </div>\
       <div class='localRes'>\
       <div class='" + localIco + "M ico left'></div>\
       <p class='left'>" + localname + "</p>\
       </div>\
       <div class='resRes'>-</div>\
       <div class='viRes'>\
       <p class='left'>" + visname + "</p>\
       <div class='" + visIco + "M ico right'></div>\
       </div>\
       <div class='fecha'>\
       <h2>" + text + "</h2>\
       <h1>" + number + "</h1>\
       </div>\
       </div>");
      }
    });
  }

  function getMes(date) {
    var monthNames = ["Ene", "Feb", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Sept", "Oct", "Nov", "Dec"];
    return monthNames[date];
  }

  function mostrarTabla(data) {
    $('#tableRes' + data + ' tbody').empty();
    $('#tablescc' + data).empty();

    if (appL.data['isTable' + data] == 1) {
      $('#tablescc' + data).append('\
        <div id="bracketc' + data + '" class="bracketsTable">\
     ');
      console.log('brakkk'+ data);
      var cont = 1;
      var idLvlActual = 0;
      $.each(appL.data['table' + data], function(index, element) {
        console.log(element);
        if (idLvlActual != element.nivel) {
          console.log(element.nivel + ' - ' + idLvlActual);
          idLvlActual = element.nivel;
          $('#bracketc' + data + '').append('<div id="lvlBra' + data + '-' + idLvlActual + '" class="level l' + (idLvlActual - 1) + '">');
        }
        var content = '\
          <div class="gameTeam ">\
              <div class="teamBra f">\
                  <div class="logoTB ' + element.localCode + 'P"></div>\
                  ' + element.localName + '\
              </div>\
              <div class="resultTB">\
                  <div class="subResultTB">\
                      ' + element.resultadoIda + '\
                  </div>\
                  <div class="subResultTB">\
                      ' + element.resultadoVuelta + '\
                  </div>\
              </div>\
              <div class="teamBra">\
                  <div class="logoTB ' + element.visCode + 'P"></div>\
                  ' + element.visName + '\
              </div>\
          </div>\
          <div class="spacelvl' + (idLvlActual - 1) + '"><br></div>\
        ';

        $('#lvlBra' + data + '-' + idLvlActual).append(content);
        cont++;
      });

    } else {
      var cont = 1;
      var grupo = -1;
      $.each(appL.data['table' + data], function(index, element) {
        // si inicia etapa tablas    
        if (grupo == -1 && element.etapa == '1') {
          grupo = 0;
          $('#tablescc' + data).append('\
            <div class="tTable"></div>\
             <table id="tableRes' + data + '-' + grupo + '" class="tableResS">\
                <thead><tr><th class="pos">POS</th><th class="equi">EQUIPOS</th><th class="">PTS</th><th class="">PJ</th><th class="">PG</th><th class="">PE</th><th class="">PP</th><th class="">DG</th></tr>\
                </thead>\
                <tbody></tbody>\
            </table>\
         ');
        } else if (grupo == -1 && element.etapa == '2') {
          grupo = 1;
          $('#tablescc' + data).append('\
        <div class="tTable">Grupo ' + grupo + '</div>\
         <table id="tableRes' + data + '-' + grupo + '" class="tableResS">\
            <thead><tr><th class="pos">POS</th><th class="equi">EQUIPOS</th><th class="">PTS</th><th class="">PJ</th><th class="">PG</th><th class="">PE</th><th class="">PP</th><th class="">DG</th></tr>\
            <tbody></tbody>\
        </table>\
     ');
        }
        if (element.grupo != grupo) {
          grupo = grupo + 1;
          $('#tablescc' + data).append('\
        <div class="tTable secondTable">Grupo ' + grupo + '</div>\
         <table id="tableRes' + data + '-' + grupo + '" class="tableResS">\
            <thead><tr><th class="pos">POS</th><th class="equi">EQUIPOS</th><th class="">PTS</th><th class="">PJ</th><th class="">PG</th><th class="">PE</th><th class="">PP</th><th class="">DG</th></tr>\
            <tbody></tbody>\
        </table>\
     ');
        }
        $('#tableRes' + data + '-' + element.grupo + ' tbody').append('\
     <tr>\
     <td class="c1 p e">' + cont + '</td>\
     <td class="c2 e">\
     <div class="' + element.team.code + 'P logoMargin">\
     </div><p class="nombreTeam">' + element.team.title + '</p>\
     </td>\
     <td class="c1 e">' + element.ptn + '</td>\
     <td class="c2 e">' + element.pj + '</td>\
     <td class="c1 e">' + element.pg + '</td>\
     <td class="c2 e">' + element.pe + '</td>\
     <td class="c1 e">' + element.pp + '</td>\
     <td class="c2 e">' + element.dg + '</td>\
     </tr>\
     ');
        cont++;
      });
    }
  }

  function mostrarBracket() {
    $('#bracket').empty();
    var cont = 1;
    var idLvlActual = 0;
    var startert=false;
    $.each(appL.data['bracket'], function(index, element) {
      // console.log(element);
      if (idLvlActual != element.nivel) {
        console.log(element.nivel + ' - ' + idLvlActual);
        idLvlActual = element.nivel;
        $('#bracket').append('<div id="lvlBra' + idLvlActual + '"class="level l' + (idLvlActual - 1) + '">');
      }
      var content = '\
          <div class="gameTeam ">\
              <div class="teamBra f">\
                  <div class="logoTB ' + element.localCode + 'P"></div>\
                  ' + element.localName + '\
              </div>\
              <div class="resultTB">\
                  ' + element.resultadoIda + ' (' + element.resultadoVuelta + ')\
              </div>\
              <div class="teamBra">\
                  <div class="logoTB ' + element.visCode + 'P"></div>\
                  ' + element.visName + '\
              </div>\
          </div>\
          <div class="spacelvl' + (idLvlActual - 1) + '"><br></div>\
        ';

      $('#lvlBra' + idLvlActual).append(content);
      cont++;
    });
  }

  function mostrarPlayers() {
    $('#plantel').empty();
    var cont = 1;
    $.each(appL.data['team'], function(index, element) {
      var dob = new Date(element.fechaNacimiento);
      var today = new Date();
      var age = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
      $('#plantel').append('\
     <div class="ccJugador">\
     <div class="foto">\
     <img src="' + appL.base + element.imagen + '"></div>\
     <div class="in2foJuga">\
     <h1>' + element.nombre + '</h1>\
     <h2>' + element.posicion + '</h2>\
     <h2>' + element.ciudad + ' - ' + element.pais + '</h2>\
     <h2>' + age + ' años - ' + element.estatura + 'mts - ' + element.peso + 'kg</h2>\
     <h2>' + element.exClub + '</h2>\
     </div>\
     </div>\
     ');
      cont++;
    });
  }

  function mostrarMinAmin() {
    var data = appL.data['min'];
    if (typeof data.titulo == 'undefined') {
      data.titulo='';
      data.golesLocal='';
      data.golesVisitante='';
      data.fecha='';
      data.titulo='';
      data.titulo='';
      data.localName= "-";
      data.visName= "-";

    }
    $('#pMin').empty();
    $('#min').empty();
    $('#pMin').append('\
    <div id="localT" class="team left">\
    <div class="' + data['localCode'] + ' ico"></div>\
    <h2>' + data.localName + '</h2>\
    </div>\
    <div class="resultadoLP">\
    <h1>' + data.titulo + '</h1>\
    <h5>' + data.golesLocal + ' - ' + data.golesVisitante + '</h5>\
    <h3>' + data.estadio + '</h3>\
    <h4>' + data.fecha + '</h4>\
    </div>\
    <div id="visT"class="team right">\
    <div class="' + data['visCode'] + ' ico"></div>\
    <h2>' + data.visName + '</h2>\
    </div>\
    ');
    $.each(data.eventos, function(index, element) {
      var ico = '';
      if (element.evento == 0) ico = "cancha";
      else if (element.evento == 1) ico = 'relog';
      else if (element.evento == 2) ico = 'tarjeta';
      else if (element.evento == 3) ico = 'balon';
      else if (element.evento == 4) ico = 'pito';
      else if (element.evento == 5) ico = 'bandera';
      $('#min').append('\
            <div class="ccMin">\
                <div class="dataMin">\
                    <h2>Minuto</h2>\
                    <h3>' + element.minuto + '</h3>\
                </div>\
                <div class="infoMin">\
                    <div class="' + ico + ' icoTT"></div>\
                    <p>\
                        ' + element.titulo + '\
                    </p>\
                </div>\
            </div>');
    });
  }

  function mostrarNoticias() {
    $.each(appL.data['iIMG'], function(index, element) {
      var url = appL.base + element['imagen'];
      $('#loadNotiCC').append("<div class='m-item'><img src='" + url + "'></div>");
    });
    $.each(appL.data['noticias'], function(index, element) {
      $('#news').append("<div class='cnoti'><div class='imgc'><div class='imgNoticia'></div><p>" + element.fecha + "</p></div><div class='textnoti'><h3>" + element.title + "</h3><p>" + element.descripcion + "</p></div></div>");
    });
    $('.m-carousel').carousel({
      dragRadius: 10,
      moveRadius: 20,
      classPrefix: undefined,
      classNames: {
        outer: "carousel",
        inner: "carousel-inner",
        item: "item",
        center: "center",
        touch: "has-touch",
        dragging: "dragging",
        active: "active"
      }
    });
    // self.setInterval(function(){moveCarousel()},1000);
  }

  function moveCarousel() {
    $('.m-carousel').carousel('next');
    self.setInterval(function() {
      moveCarousel()
    }, 1000);
  }

})(jQuery);
