var menLoc, menDiv;
menLoc = firstLoc;

var cal;
var months = ["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"];
var longMonths = ['ENERO','FEBRERO','MARZO','ABRIL','MAYO','JUNIO','JULIO','AGOSTO','SEPTIEMBRE','OCTUBRE','NOVIEMBRE','DICIEMBRE'];

$(function(){
	menDiv = $("#mensaje");
	var options = {
		days: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
		sdays: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'S&aacute;'],
		months: longMonths,
		tableTitle: 'Calendario',
		disabledDays: [0],
		prevImg: 'images/calPrev.gif',
		nextImg: 'images/calNext.gif',
		prevImgDis: 'images/calPrevF.gif',
		nextImgDis: 'images/calNextF.gif',
		startDate: new Date(2004, 2, 1),
		endDate: today,
		selDate: (firstLoc.length == 13 ? stringToDate(firstLoc) : today),
		today: today
	};
	cal = new $.calendar('#cal', getMessage, options);
	$("#mensaje a:contains('imprimir')").css({'float': 'right', clear: 'right'}).before($("#addthiscon")).prev().show();
	mediaInit();
	$.history.initialize(function(hash){
		if (hash == 'faq') {
			loadFAQ(false);
		} else if (hash.indexOf('caso') == 0) {
			var casoNum = 0;
			if (hash.length > 4)
				casoNum = hash.substring(4) - 0;
			loadCaso(false, casoNum);
		} else
			cal.setSelectedDate(stringToDate(hash.length > 0 ? hash : firstLoc), true, false);
	});
	$("#pf").click(function(){
		loadFAQ(true);
		return false;
	});
	$("#cs a").click(function(){
		loadCaso(true, 0);
		return false;
	});
	$("#csd a").click(function(){
		window.open("casos.aspx","Survey","scrollbars=yes,width=500,height=550");
		return false;
	});
	$(".tracts a").click(function(){
		var wh = this.href.indexOf("familia") > -1 ? {w: 620, h: 470} : {w: 600, h: 400};
		window.open(this.href,'Preguntas','scrollbars=yes,width='+wh.w+',height='+wh.h);
		return false;
	});
	findCasoLinks();
	$("#q,#email").focus(function(){
		curForm = $(this).parent().get(0);
	}).blur(function(){
		curForm = null;
	}).get(0).focus();
	showCalMsg();
});
$.ajaxSetup({timeout: 6000});
$().ajaxError(function(req, s){
	if (s.url.indexOf("mensaje") > -1)
		location.href = "main.aspx?ID=" + s.url.substring(16);
});
function loading() {
	menDiv.html('<div class="load"><img src="images/indicator.gif" /> Abriendo...</div>');
}
function loadFAQ(addToHistory) {
	loading();
	cal.setSelectedDate(null);
	menDiv.load("faq.html", function(){
		initFAQ();
		if (addToHistory)
			$.history.update('faq');
	});
}
function initFAQ() {
	$("#mensaje h4 a").toggle(function(){
		$(this).parent().next().slideDown();
		return false;
	}, function(){
		$(this).parent().next().slideUp();
		return false;
	});
}
function loadCaso(addToHistory, casoNum) {
	loading();
	cal.setSelectedDate(null);
	var casourl = "caso.aspx?";
	if (casoNum > 0)
		casourl += "ID=" + casoNum + "&";
	menDiv.load(casourl + "d=" + (new Date() - 0), function(){
		if (addToHistory)
			$.history.update('caso' + (casoNum > 0 ? casoNum : ''));
		$("#casonav select").change(function(){
			loadCaso(true, $(this).val() - 0);
		});
	});
}
function findCasoLinks() {
	$("a[href*='main.aspx?c=']", menDiv).click(function(){
		loadCaso(true, this.href.substring(this.href.indexOf("=") + 1) - 0);
		window.scrollTo(0, 0);
		return false;
	});
}
function getMessage(date, addToHistory) {
	loading();
	var id = date instanceof Date ? dateToString(date) : date;
	menDiv.load("mensaje.ashx?ID=" + id, function(){
		menLoc = id + ".htm";
		if (addToHistory)
			$.history.update(id);
		findCasoLinks();
	}, true);
	changeLinks(date);
}
function dateToString(date) {
	var day = date.getDate();
	if (day < 10)
		day = "0" + day;
	return date.getFullYear() + months[date.getMonth()] + day;
}
function dateToLongString(date) {
	return date.getFullYear() + "/" + months[date.getMonth()] + "/" + dateToString(date);
}
function stringToDate(str) {
	var month = str.substring(4, 7).toLowerCase();
	for (var i = 0; i < 12; i++)
		if (months[i] == month)
			return new Date(str.substring(0, 4), i, str.substring(7, 9));
	return null;
}

function printWindow() {
	window.open('Print.aspx?ID='+menLoc,'Imprimir','scrollbars=yes,width=738,height=554');
}
var curForm;
$(document).keydown(function(e){
	if (e.keyCode == 13){
		if (curForm)
			curForm.submit();
		return false;
	}
});

var audio, video, vidWindow;

function mediaInit() {
	audio = $("#hlAudio"); //.click(launchAudio);
	video = $("#hlVideo");
	vidWindow = $("#vidWindow");
	if (stringToDate(firstLoc) >= flvStart)
		video.click(launchVideo);
	if (initVideo)
		video.click();
}
//function launchAudio(){return false;}
var loadedVideo = false, firstLoad = true, curVid;
function launchVideo() {
	var date = stringToDate(menLoc);
	$("h3", vidWindow).html(date.getDate() + " de " + longMonths[date.getMonth()].toLowerCase() + " de " + date.getFullYear());
	if (vidWindow.is(":hidden")) {
		if (!loadedVideo) {
			loadedVideo = true;
			$(".close", vidWindow).click(function(){
				$("#flvplayer")[0].sendEvent("stop");
				vidWindow.hide();
			});
			var so = new SWFObject('flvplayer.swf', 'flvplayer', '320', '260', '8');
			so.addParam("allowfullscreen", "true");
			so.useExpressInstall('expressinstall.swf');
			so.addVariable("file", this.href);
			curVid = this.href;
			so.addVariable("autostart", "true");
			so.addVariable("enablejs", "true");
			so.write('vidPlayer');
		}
		vidWindow.show();
	}
	if (!firstLoad) {
		if (this.href != curVid) {
			curVid = this.href;
			setTimeout(function(){
				$("#flvplayer")[0].loadFile({file: curVid});
			}, 250);
		}
	} else
		firstLoad = false;
	return false;
}
var flvStart = new Date(2007, 5, 25);
function changeLinks(date) {
	audio.attr("href", "mensajes/" + dateToLongString(date) + ".mp3");
	if (date < flvStart)
		video.unbind().attr("href", "download.ashx?ID=" + dateToString(date) + "v.asx");
	else
		video.unbind().attr("href", "http://video.conciencia.net/" + dateToString(date) + ".flv").click(launchVideo);
}

function showCalMsg() {
	if ($.cookie.get("SeenCalMsg") != "y") {
		var popup = $("#newmsg");
		var to;
		var closer = $(".close", popup).click(function(){
			clearTimeout(to);
			popup.fadeOut();
		});
		setTimeout(function(){
			popup.fadeIn();
			to = setTimeout(function(){
				closer.click();
			}, 30000);
		}, 4000);
	}
	$.cookie.setInfo("SeenCalMsg", "y", {expires: 300});
}