//jQuery.noConflict();

//alert(document.cookie);

function isset(  ){
    // !No description available for isset. @php.js developers: Please update the function summary text file.
    // 
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/isset
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: FremyCompany
    // +   improved by: Onno Marsman
    // *     example 1: isset( undefined, true);
    // *     returns 1: false
    // *     example 2: isset( 'Kevin van Zonneveld' );
    // *     returns 2: true
    
    var a=arguments, l=a.length, i=0;
    
    if (l===0) {
        throw new Error('Empty isset'); 
    }
    
    while (i!==l) {
        if (typeof(a[i])=='undefined' || a[i]===null) { 
            return false; 
        } else { 
            i++; 
        }
    }
    return true;
}

function readCookie(name){
  var ca = document.cookie.split(';');
  var nameEQ = name + "=";
  for(var i=0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
  return null;
}


var estadoUsuario= "";
var swEnvio= false;

function clearText(field){
	if (field.defaultValue == field.value) field.value = '';
	else if (field.value == '') field.value = field.defaultValue;
}

function caritaUp(id){
	$(id).animate({
		top: -5
	}, 200, 'easeOutBounce');
}

function caritaDown(id){
	$(id).animate({
		top: 0
	}, 200, 'easeOutBounce');
}

function tooltipCaritas(estado){
	$('#'+estado).qtip({
		content: '<img src="images/'+estado+'.gif" />',
		position: {
			corner: {
				tooltip: 'bottomMiddle', // Use the corner...
				target: 'topMiddle' // ...and opposite corner
			}
		},
		show: { ready: true }, // Show the tooltips when they're ready
		style: {
			width: 150,
			border: {
				width: 2,
				radius: 5,
				color: '#ffffff'
			},
			padding: 15, 
			textAlign: 'center',
			fontWeight: 'bold',
			tip: true, // Give it a speech bubble tip with automatic corner detection
			name: 'light' // Style it according to the preset 'cream' style
		}

	});
}

function muestraCajaCuentanos(){
	$("#cuentanos").css("visibility","visible");
}

function ticketOff(){
	$("#ticketFeliz").attr("src","images/ticket_off.png");
	$("#ticketNeutro").attr("src","images/ticket_off.png");
	$("#ticketTriste").attr("src","images/ticket_off.png");
}

function gAnalytics(page){
	pageTracker._trackPageview(page);
}


function ticketOn(estado){
	if(estado == "#ticketFeliz"){
		gAnalytics("/SELECCION_CARA_FELIZ");
		estadoUsuario= "feliz";
	}else if(estado == "#ticketNeutro"){
		gAnalytics("/SELECCION_CARA_NOPASANA");
		estadoUsuario= "nopasana";
	}else if(estado == "#ticketTriste"){
		gAnalytics("/SELECCION_CARA_TRISTE");
		estadoUsuario= "triste";
	}
	
	ticketOff();
	$(estado).attr("src","images/ticket_on.png");
	muestraCajaCuentanos();
}

function desabilitaElementosHome(){
	$("#txtCuentanosPorque").attr("disabled","false");
	$("#ticketFeliz").attr("disabled","false");
	$("#ticketNeutro").attr("disabled","false");
	$("#ticketTriste").attr("disabled","false");
	$("#feliz").attr("disabled","false");
	$("#neutro").attr("disabled","false");
	$("#triste").attr("disabled","false");
}

function habilitaElementosHome(){
	$("#txtCuentanosPorque").attr("disabled","true");
	$("#ticketFeliz").attr("disabled","true");
	$("#ticketNeutro").attr("disabled","true");
	$("#ticketTriste").attr("disabled","true");
	$("#feliz").attr("disabled","true");
	$("#neutro").attr("disabled","true");
	$("#triste").attr("disabled","true");
}

function yaVotaste(){
	$('#txtCuentanosPorque').qtip({
		content: '<p class="yavotaste">Lo sentimos, ya compartiste tu estado de animo.</p><p class="yavotaste">Puedes volver a expresarte dentro de la pr&oacute;xima hora.</p>',
		position: {
		  corner: {
		     tooltip: 'topMiddle', // Use the corner...
		     target: 'bottomMiddle' // ...and opposite corner
		  }
		},
		show: {
			delay: 100, 
		  when: false, // Don't specify a show event
		  ready: true // Show the tooltip when ready
		},
		hide: { delay: 1000 }, // Don't specify a hide event
		style: {
			width: 450,
		  border: {
		     width: 3,
		     radius: 10
		  },
		  padding: 5, 
		  textAlign: 'center',
		  tip: true, // Give it a speech bubble tip with automatic corner detection
		  name: 'green' // Style it according to the preset 'cream' style
		}
	});
}

function ocultaToolTipEnvio(){
	$('#botonEnvio').qtip({ hide: { delay: 500 } });
}

function updateOk(){
	gAnalytics("/PUBLICACION_DE_ESTADO");
	swEnvio= true;
	//$('#txtCuentanosPorque').qtip({ hide: true; });
	desabilitaElementosHome();
	
	$('#botonEnvio').qtip({
		content: 'Enviando tu estado. <br /><img src="images/loading.gif" />',
		position: {
		  corner: {
		     tooltip: 'leftMiddle', // Use the corner...
		     target: 'rightMiddle' // ...and opposite corner
		  }
		},
		show: {
			delay: 100, 
		  when: false, // Don't specify a show event
		  ready: true // Show the tooltip when ready
		},
		hide: false, // Don't specify a hide event
		style: {
		  border: {
		     width: 5,
		     radius: 10
		  },
		  padding: 3, 
		  textAlign: 'center',
		  tip: true, // Give it a speech bubble tip with automatic corner detection
		  name: 'cream' // Style it according to the preset 'cream' style
		}
	
	});
}

function fbInicioSession(){
  FB.ensureInit(function() {
      FB.Connect.get_status().waitUntilReady(function(status) {
          if(status != FB.ConnectState.userNotLoggedIn) {
						//
						gAnalytics("/FBCONNECT_USUARIO_YA_LOGEADO");
          }else{
          	gAnalytics("/FBCONNECT_INICIO_SESSION");
          	FB.Connect.requireSession(function(){ fbConnect(); });
          }
        });
    });
}

function estadisticas(estado){
	gAnalytics("/REDIRIGE_A_ESTADISTICAS");
	window.location.href= "estadisticas";
}

////INIT FACEBOOK
	function showFeedDialog(fbEstado, fbPorque, fbCara){
		gAnalytics("/FBCONNECT_PUBLICO_EN_MURO");		
		fbInicioSession();
    
		var template_bundle_id = 100323867949;
		
		if(fbEstado == "feliz"){
			fbEstado= "Feliz";
			fbCara= "feliz";
		}else if(fbEstado == "nopasana"){
			fbEstado= "No Pasa Na'";
			fbCara= "nada";
		}else if(fbEstado == "triste"){
			fbEstado= "Triste";
			fbCara= "triste";
		}
		
		var template_data = {"estado":fbEstado,"porque":fbPorque,"images":[{"src":"http://www.sonriehoy.cl/images/animo_"+fbCara+".png", "href":"http://apps.facebook.com/sonriehoy/"}]};
		FB.Connect.showFeedDialog(template_bundle_id, template_data, null, null, null,FB.RequireConnect.require, postForm);
	}
	
	function postForm(){
		//
	}
////END FACEBOOK
				
function updateEstado(){
	if(swEnvio == false){
		if($("#txtCuentanosPorque").val() != "Cu\u00E9ntanos por qu\u00E9"){
			if(!ck){
				//Envio datos
				$.post("process/index.php", { estado: estadoUsuario, 
					porque: $('#txtCuentanosPorque').val(), 
					fbVar_uid:fb_uid, 
					fbVar_name:fb_name, 
					fbVar_pic_square:fb_pic_square, 
					fbVar_birthday_date:fb_birthday_date, 
					fbVar_sex:fb_sex, 
					fbVar_username:fb_username,
					fbVar_interests:fb_interests,
					fbVar_activities:fb_activities,
					fbVar_city:fb_city,
					fbVar_state:fb_state,
					fbVar_country:fb_country,
					fbVar_zip:fb_zip},
				  function(data){
				  	alert(data);				  	
				    if(data == 100){ //estado ok
				    	updateOk();
				    	estadisticas();
				    }else if(data == 200){ //ya votaste!!!
				    	gAnalytics("/AVISO_YA_VOTASTE_IP");
				    	yaVotaste();
				    }
				  }, "html");
			}else{
				gAnalytics("/AVISO_YA_VOTASTE_COOKIE");
				yaVotaste();
			}
		}else{
			gAnalytics("/ERROR_NO_INGRESO_LA_RAZON");
			$('#txtCuentanosPorque').qtip({
				content: 'Debes ingresar la raz&oacute;n.',
				position: {
				  corner: {
				     tooltip: 'topMiddle', // Use the corner...
				     target: 'bottomMiddle' // ...and opposite corner
				  }
				},
				show: {
					delay: 100, 
				  when: false, // Don't specify a show event
				  ready: true // Show the tooltip when ready
				},
				hide: { delay: 1000 }, // Don't specify a hide event
				style: {
				  border: {
				     width: 3,
				     radius: 10
				  },
				  padding: 5, 
				  textAlign: 'center',
				  tip: true, // Give it a speech bubble tip with automatic corner detection
				  name: 'red' // Style it according to the preset 'cream' style
				}
			});
		}
	}
}

function loading(){
	var load= "<img src=\"images/loading.gif\" border=\"0\" />";
	
	return load;
}

function resumenEstadistica(vVista){
		gAnalytics("/RANKING_VISTA_"+vVista);
	
		$(".fondoPrimero").html(loading());
		$(".fondoSegundo").html(loading());
		$(".fondoTercero").html(loading());
		
    
    var cache= Math.random();
    $.getJSON("process/resumenEstadistica.php?cache="+cache+"&vista="+vVista,
        function(data){
					var cajasEstados=new Array(".fondoPrimero",".fondoSegundo",".fondoTercero");
					var carasEstados=new Array(".caraPrimero",".caraSegundo",".caraTercero");
					var cntCajas= 0;
					var totalDatos= 0;
					var cargaCaraChile= 0;
					var cnt=1;
					var animoCara= "";
					
        	if(vVista == "hoy"){
        		if(data[0].estado == "feliz"){
        			$(".cajaAnimoChile").html("FELIZ");
        			$("#txtOcultoAnimoChile").val("FELIZ");
        			$(".cajaCaraChile").html("<img src='images/caja_chile_animo_feliz.gif' />");
        		}else if(data[0].estado == "nopasana"){
        			$(".cajaAnimoChile").html("NO PASA NA'");
        			$("#txtOcultoAnimoChile").val("NO PASA NA");
        			$(".cajaCaraChile").html("<img src='images/caja_chile_animo_nopasana.gif' />");
        		}else if(data[0].estado == "triste"){
        			$(".cajaAnimoChile").html("TRISTE");
        			$("#txtOcultoAnimoChile").val("TRISTE");
        			$(".cajaCaraChile").html("<img src='images/caja_chile_animo_triste.gif' />");
        		}
        	}
					
          $.each(data, function(i,item){
          	totalDatos= parseInt(data[0].cuenta) + parseInt(data[1].cuenta) + parseInt(data[2].cuenta);
						
          	if(item.estado == "feliz"){
          		animoCara= "Feliz";
          		$(carasEstados[cntCajas]).css("background","url(images/ranking_feliz.gif) no-repeat");
          		$(carasEstados[cntCajas]).fadeOut(100).fadeIn(500);
          	}else if(item.estado == "nopasana"){
          		animoCara= "Nopasana";
          		$(carasEstados[cntCajas]).css("background","url(images/ranking_nada.gif) no-repeat");
          		$(carasEstados[cntCajas]).fadeOut(100).fadeIn(500);
          	}else if(item.estado == "triste"){
          		animoCara= "Triste";
          		$(carasEstados[cntCajas]).css("background","url(images/ranking_triste.gif) no-repeat");
          		$(carasEstados[cntCajas]).fadeOut(100).fadeIn(500);
          	}
          	
            //$(cajasEstados[cntCajas]).html("<a href='listado.php?estado="+animoCara+"&pos="+cnt+"' onclick=\"javascript:window.location.href='#top'\" rel=\"shadowbox;width=600;height=500;\" id='posicion"+cnt+"' class='linkCarasAnimos'><b>" +Math.round((item.cuenta / totalDatos) * 100) + "%</b> <span class='textoChico'>("+item.cuenta+" p)</span></a>");
            $(cajasEstados[cntCajas]).html("<a href=\"javascript:abreListado('"+animoCara+"','"+cnt+"');\" onclick=\"javascript:window.location.href='#top'\" rel=\"shadowbox;width=600;height=500;\" id='posicion"+cnt+"' class='linkCarasAnimos'><b>" +Math.round((item.cuenta / totalDatos) * 100) + "%</b> <span class='textoChico'>("+item.cuenta+" p)</span></a>");
            cntCajas++;
            cnt++;
          });
        });
}

function abreListado(estado,pos){
	gAnalytics("/LISTADO_RAZONES_"+estado);
	
	var tituloEstado= "";
	if(estado == "Feliz"){
		tituloEstado= "Feliz";
	}else if(estado == "Nopasana"){
		tituloEstado= "No pasa na";
	}else if(estado == "Triste"){
		tituloEstado= "Triste";
	}
	
	Shadowbox.open({
	    content:    'listado.php?estado='+estado+'&pos='+pos,
	    player:     "iframe",
	    title:      tituloEstado,
	    height:     400,
	    width:      550
	});
}

function live(){
	for(var i=1; i<=7; i++){
		$("#live"+i).html(loading());
	}
	
	var cache= Math.random();
	
	$.get("process/live.php?cache="+cache, function(data){
  	//$("#live"+id).html(data);
  	var id= 1;
		$(data).find('mensajes').each(function(){
			//alert($(this).find('estado').text());
			$("#live"+id).html("<div style='background: url(images/razon_"+$(this).find('estado').text()+".png) no-repeat; padding-left: 35px; padding-bottom: 50px;'>" + $(this).find('porque').text() + "</div>");
			id++;
		});
		//alert(data);
	},"xml");
}

//$(document).ready(function(){
$(window).load(function(){
	var swTicketFeliz= false;
	var swTicketNeutro= false;
	var swTicketTriste= false;

	$("#txtCuentanosPorque").charCounter(50, {
		container: "#contadorCaracteres",
		format: "%1"
	});
	
	$("#botonEnvio").hover(function(event){
		$("#botonEnvio").css("background","url(images/flecha_on.png)");
	},function(){
		$("#botonEnvio").css("background","url(images/flecha_off.png)");
	});
	
	$("#botonEnvio").click(function(){
		updateEstado();
	});
	
	$("#txtCuentanosPorque").keypress(function(e){
		if(e.which == 13) updateEstado();
	});

	
	//ROLLOVER, ROLLOUT y CLICK CARITAS
	$("#feliz").click(function(){ ticketOn("#ticketFeliz");	});
	$("#neutro").click(function(){ ticketOn("#ticketNeutro");	});
	$("#triste").click(function(){ ticketOn("#ticketTriste"); });

	$("#ticketFeliz").click(function(){ ticketOn("#ticketFeliz");	});
	$("#ticketNeutro").click(function(){ ticketOn("#ticketNeutro");	});
	$("#ticketTriste").click(function(){ ticketOn("#ticketTriste");	});

	$("#feliz").hover(function(event){
		caritaUp(this);
	},function(){
		caritaDown(this);
	});
	
	$("#neutro").hover(function(event){
		caritaUp(this);
	},function(){
		caritaDown(this);
	});
	
	$("#triste").hover(function(event){
		caritaUp(this);
	},function(){
		caritaDown(this);
	});
	
	$("#btnFacebookApp").hover(function(event){
		$("#btnFacebookApp").attr("src","images/btn_fb_on.gif");
	},function(){
		$("#btnFacebookApp").attr("src","images/btn_fb_off.gif");
	});
	
	$("#btnTwitter").hover(function(event){
		$("#btnTwitter").attr("src","images/twitter_on.gif");
	},function(){
		$("#btnTwitter").attr("src","images/twitter_off.gif");
	});
	
	$("#btnGrafico").hover(function(event){
		$("#btnGrafico").attr("src","images/estadisticas_on.gif");
	},function(){
		$("#btnGrafico").attr("src","images/estadisticas_off.gif");
	});
	
	//ANIMO CHILE
	$("#btnFacebookAnimoChile").hover(function(event){
		$("#btnFacebookAnimoChile").attr("src","images/fb_on.gif");
	},function(){
		$("#btnFacebookAnimoChile").attr("src","images/fb_off.gif");
	});
	
	$("#btnTwitterAnimoChile").hover(function(event){
		$("#btnTwitterAnimoChile").attr("src","images/tw_on.gif");
	},function(){
		$("#btnTwitterAnimoChile").attr("src","images/tw_off.gif");
	});
	
	//ANIMO MIO
	$("#btnFacebookTuAnimo").hover(function(event){
		$("#btnFacebookTuAnimo").attr("src","images/fb_on.gif");
	},function(){
		$("#btnFacebookTuAnimo").attr("src","images/fb_off.gif");
	});
	
	$("#btnTwitterTuAnimo").hover(function(event){
		$("#btnTwitterTuAnimo").attr("src","images/tw_on.gif");
	},function(){
		$("#btnTwitterTuAnimo").attr("src","images/tw_off.gif");
	});
	
	//VOLVER GRAFICO
	$("#btnVolverGrafico").hover(function(event){
		$("#btnVolverGrafico").attr("src","images/volver_on.png");
	},function(){
		$("#btnVolverGrafico").attr("src","images/volver_off.png");
	});
	
	//DETALLE DE ESTADOS
	$("#posicion1").hover(function(event){
		//$("#ranking").css("background-position","0px -75px");
		$("#ranking").css("background","url(images/ranking1.gif) no-repeat");
	},function(){
		//$("#ranking").css("background-position","0 0");
		$("#ranking").css("background","url(images/ranking.gif) no-repeat");
	});
	
	$("#posicion2").hover(function(event){
		//$("#ranking").css("background-position","0px -150px");
		$("#ranking").css("background","url(images/ranking2.gif) no-repeat");
	},function(){
		//$("#ranking").css("background-position","0 0");
		$("#ranking").css("background","url(images/ranking.gif) no-repeat");
	});
	
	$("#posicion3").hover(function(event){
		//$("#ranking").css("background-position","0px -225px");
		$("#ranking").css("background","url(images/ranking3.gif) no-repeat");
	},function(){
		//$("#ranking").css("background-position","0 0");
		$("#ranking").css("background","url(images/ranking.gif) no-repeat");
	});

	

});