var connected = false;

var Index = {
  url : "",
  urlBase : "../",
  user: "",
  timer: null,
  stompSessionId: -1,
  onlineTimer: null,
  onlineCounter: 0,
  nickname: "",
  nnR: false,

  currentSlideShow: "",
  currentSlideIndex: 0,
  hash: "",

  connected: false,
  stomp: null,

  init: function(){
    Index.banners();
    Index.addHandlers();
    Index.loadSlideShow();

    // starting STOMP
    Index.startStomp();
    Index.onlineTimer = setInterval(Index.isOnline, 1000);

  },
  startStomp: function(){
        Index.stomp = new STOMPClient();
  		Index.stomp.onopen = function() {};
		Index.stomp.onclose = function(c) {
            Index.connected = false;
            connected = false;
            clearInterval(Index.timer);
        };
		Index.stomp.onerror = function(error) { alert("Error: " + error);	};
		Index.stomp.onerrorframe = function(frame) { alert("Error: " + frame.body); };
		Index.stomp.onmessageframe = Index.handleMsg;

		Index.stomp.onconnectedframe = function(frame) {
			Index.stompSessionId = frame['headers']['session'];
			Index.stomp.subscribe("/stream/gartv_"+Index.user);
            Index.connected = true;
            connected = true;
            Index.heartbeat();
            Index.timer = setInterval(Index.heartbeat, 30000);
		};
        Index.stompConnect();
  },
  stompConnect: function(){
      Index.stomp.connect('localhost', 61613, 'guest', 'guest');
  },
  isOnline: function(){
     Index.onlineCounter--;
     if(Index.onlineCounter<=0){
       setAdminStatus("N");
     }else{
       setAdminStatus("Y");
     }
  },
  handleMsg: function(frame){
    json = eval('(' + frame.body + ')');
    if (json.type=="chatEnter"){
        enteredChat(unescape(json.nick), json.created);
    }
    if (json.type=="chat"){
        receiveMsg(unescape(json.msg), unescape(json.from), json.created);
    }
    if (json.type=="iHeartBeat"){
       Index.onlineCounter=30;
       if ((json.nnR.length>0)&&(!Index.nnR)){
         // verificar se est� aqui
         var tot = json.nnR.length;
         for(var i=0; i<tot; i++){
             if (Index.stompSessionId==json.nnR[i]){
               Index.nnR = true;
             }
         }
       }
    }
    if (json.type=="slideShowGoTo"){
       slideShowGoTo(json.slideShowId, json.slideShowIndex);
    }
    if (json.type=="setMarqueeMsg"){
      setMarqueeMsg(json.msg);
    }
    if (json.type=="startAudioTransmission"){
      startAudioTransmission();
    }
    if (json.type=="stopAudioTransmission"){
      stopAudioTransmission();
    }
    if (json.type=="startVideoTransmission"){
      startVideoTransmission();
    }
    if (json.type=="stopVideoTransmission"){
      stopVideoTransmission();
    }
    if (json.type=="blockUser"){
      Index.blockUser(json.user);
    }
    if (json.type=="requestNN"){
        if (json.requestId == Index.stompSessionId){
            Index.stomp.send("{ type: \"updateNN\", id: "+Index.stompSessionId+", nn: \""+Index.nickname+"\"}", "/stream/gartv_"+Index.user);
        }
    }
  },
  heartbeat: function(){
    if (connected){
        if (Index.nickname==""){
            Index.stomp.send("{ type: \"heartBeat\", id: "+Index.stompSessionId+"}", "/stream/gartv_"+Index.user);
        }else{
            if (Index.nnR){
                Index.stomp.send("{ type: \"heartBeatC\", id: "+Index.stompSessionId+", nick: \""+Index.nickname+"\" }", "/stream/gartv_"+Index.user);
                Index.nnR = false;
            }else{
                Index.stomp.send("{ type: \"heartBeatC\", id: "+Index.stompSessionId+"}", "/stream/gartv_"+Index.user);
            }
        }
    }else{
      setTimeout(Index.stompConnect, 5000);
    }
  },
  banners: function(){
    $('#banners ul').cycle({
      fx:    'fade',
      speed:  2500,
      timeout: 10000
    });
  },
  addHandlers: function(){
    $("#btnEnter").click(function(){
        //Index.enterChat();
    });

    $("#btnSend").click(Index.sendMessage);

    $("#frmChat").submit( function(){
          Index.sendMessage();
          return false;
    });
    $("#frmEntrar").submit(function(){
        Index.enterChat();
        return false;
    });
    $("#btnGartv").click(function(){
      window.open(this);
      return false;
    });
  },

  enterChat: function(){
    if (Index.connected){
       if ($("#nick").val()==""){
         alert("Por favor, informe um apelido.");
       }else{
         $.post(Index.urlBase+'cs.php?usr='+Index.user,{ 'msg' : Index.stringfy({type: "chatEnter", nick: $("#nick").val()})});
         Index.nickname = $("#nick").val();
         $("#frmEntrar").hide();
         $("#mensagens").show();
         $("#frmChat").show();
       }
     }
  },
  sendMessage: function(){
    msg = $("#newMsg").val();
    if (msg!=""){
      $("#newMsg").val("");
      $.post(Index.urlBase+'cs.php?usr='+Index.user,{ 'msg' : Index.stringfy({type: "chat", msg: msg})});
      return false;
    }
  },

  stringfy: function(item){
     msg = "";
     msg+=item.type+"|";
     if (item.type=="chatEnter"){
       msg+= escape(item.nick);
     }else if(item.type="chat"){
       msg+= escape(item.msg);
     }
    return msg;
  },
  loadSlideShow: function(){
    if (Index.currentSlideShow!=""){
        $.get(Index.url+"slideShows/getSlideShow/"+Index.currentSlideShow, null, Index.slideShowLoaded);
    }
  },
  slideShowLoaded: function(d){
    $("#slide").html(d);
    $('#slide ul').cycle({
      fx:    'fade',
      speed:  2500,
      timeout: 0,
      startingSlide: Index.currentSlideIndex
    });
  },
  playerLoaded: function(d){
    $("#player").html(d);
  },
  scroll: function(){
    if ($("#rolar").attr("checked")){
        var objDiv = document.getElementById("mensagens");
        objDiv.scrollTop = objDiv.scrollHeight;
	}
  },
  blockUser: function(id){
    if (Index.stompSessionId==id){
        $("#sendMsg").hide();
    }
  },
  assistirVideo: function(id){
    window.open(Index.url+"assistir/getPlayerVideo/"+id, "frameVideo");
  },
  videoPlayerLoaded: function(d){
    $("#player").html(d);
  },
  assistirAoVivo: function(){
    window.open(Index.url+"assistir/getPlayer/", "frameVideo");
  },
  oferta: function(user){
    window.open(Index.url+"oferta", "oferta", "width=500, height=500,location=no,toolbar=no,menubar=no");
  },
  biblia: function(){
    window.open(Index.url+"biblia", "biblia", "width=500, height=700,location=no,toolbar=no,menubar=no, scrollbars=yes, left=500");
  },
  testemunho: function(){
    window.open(Index.url+"testemunhos", "testemunho", "width=600, height=500,location=no,toolbar=no,menubar=no, scrollbars=yes");
  },
  oracao: function(){
    window.open(Index.url+"pedidos/novo", "oracao", "width=600, height=500,location=no,toolbar=no,menubar=no, scrollbars=yes");
  }
}

$().ready(function(){
    Index.init();
});

Orbited.settings.port = 8000;
TCPSocket = Orbited.TCPSocket;

function receiveMsg(msg, from, created){
    $("#mensagens").append("<p>("+created+") <span class='user'>"+from+"</span> disse: "+msg+"</p>");
    Index.scroll();
}
function enteredChat(nick, created){
    $("#mensagens").append("<p>("+created+") <span class='user'>"+nick+"</span> entrou.</p>");
    Index.scroll();
}

function slideShowGoTo(slideShow, ind){
  ind = parseInt(ind);
  Index.currentSlideIndex = ind;
  if (slideShow!=Index.currentSlideShow){
    Index.currentSlideShow = slideShow;
    Index.loadSlideShow();

  }else{
      $("#slide ul").cycle(ind);
      slideAtual = ind;
      $("#slideD").html("Slide "+(slideAtual+1));
  }
}

function getTextFromAS(a){
  $("#mensagens").append("<p>"+a+"</p>");
}

function thisMovie(movieName) {
   if (navigator.appName.indexOf("Microsoft") != -1) {
       return window[movieName];

   } else {
       return document[movieName];
   }
}

function startAudioTransmission(){
  window.open(Index.url+"assistir/getPlayer/R", "frameVideo");
}
function stopAudioTransmission(){
  window.open(Index.url+"assistir/getPlayer/N", "frameVideo");
}
function startVideoTransmission(){
  window.open(Index.url+"assistir/getPlayer/T", "frameVideo");
}
function stopVideoTransmission(){
  window.open(Index.url+"assistir/getPlayer/N", "frameVideo");
}
function setMarqueeMsg(msg){
  thisMovie("marquee").setTexto(msg);
}
function blockUser(id){
  Index.blockUser(id);
}
function setAdminStatus(status){
  if (status=="Y"){
    $("#statusAdm").html("<span class=\"online\">igreja online</span>");
  }else{
    $("#statusAdm").html("<span class=\"offline\">igreja offline</span>");
  }
}
