var totalDays = 0;
var initialDayWidth = 0;
var slider;
// maxium dagen in dag overzicht
var maxDayView = 9;
var startDateAgenda;

function initAgenda() {
    slider = $("#slider");
    var width = (initialDayWidth * (totalDays - 1));
    $(slider).css("width", width + "px");
    $("#balk").css("width", width + 10 + "px");

    setDayWidth();
    setSliderDays();

    $(slider).draggable({
        axis: "x",
        containment: "parent",
        grid: [initialDayWidth, initialDayWidth],
        start: function(size) {
            $(this).css("opacity", "0.7");
            $("#daycontainer").empty();
        },
       // drag: function(e, ui) {
//			moveAgendacontainer();
//			
//        },
        stop: function(e, ui) {
            $(this).css("opacity", "1");
            setSliderDays();
			//setDayWidth();
			moveAgendacontainer();
        }
    });

    $(slider).resizable({
        handles: "e,w",
        containment: "parent",
        minWidth: (initialDayWidth * 3),
        grid: [initialDayWidth, initialDayWidth],
        start: function(size) {
            $(this).css("opacity", "0.7");
            $("#daycontainer").empty();
        },
//        resize: function(size) {
//			$("#agenda-holder .uitvoering .visual .image")
//				.css("height",$(".uitvoering .visual .image")
//				.width()+"px");
//        },
        stop: function(e, ui) {
            $(this).css("opacity", "1");
			setDayWidth();
            setSliderDays();
			
        }
    });

    // Done setting up the calendar, now grab the agenda
    $.ajax({
        type: "POST",
        url: "Services/agenda.asmx/GetAllAgenda",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: fillAgenda
		
    });
	$("#calendar-container .dag-th").click(function(){
			whichday = $("#calendar-container  th").index(this) - 1;
			setDayWidth(3,whichday);
		});
	$("#agenda-container .dag-th").click(function(){
			whichday = $("#agenda-container th").index(this) - 1;
			setDayWidth(3,whichday);
		});
	$("#slider ~ .balkdag").click(function(){
			//alert($("#slider .balkdag").length)
			whichday = ( $("#balk .balkdag").index(this) -  $("#slider .balkdag").length ) - 1;
			setDayWidth(3,whichday);
		});
	
	$("#slider ~ .balkdag:first").addClass("bd_first");
}

function setSliderDays(x,y) {
	if (x > 0){
		var numDays = x;
		var start = y + 1;
	} else {
		var numDays = getNumSelectDays();
		var start = getDaysFromLeft() + 1;
	}
    
    for (i = 1; i <= numDays; i++) {
        var day = $("#balk .balkdag:nth-child(" + (start + i) + ")").clone();
        $("#daycontainer").append(day);
    }
}
function setDayWidth(a,b) { // a = aantal te tonen dagen  || b = begindag
	//$("#agenda-holder .uitvoering .visual .image").css("height",$(".uitvoering .visual .image").width()+"px");
	if (a>0){
	    var numDays = a;
        var start = b;	
	    fromLeft = b * initialDayWidth; 
	    theWidth = a * initialDayWidth; 
		$("#slider").css({
			 'top' : '0px',
			 'left' : fromLeft+'px',
			 'width':theWidth+1+'px'
		});
		$("#daycontainer").empty();
	    setSliderDays(numDays,start);
	} else {
        var numDays = getNumSelectDays();
        var start = getDaysFromLeft();
	}
	
	showArrows();
    if (numDays <= maxDayView) {
			$("#agenda-container").attr("class","width-"+numDays);
			$("#agenda-container").css("display", "block");
			$("#calendar-container").css("display", "none");
			$("#locatie_selector_container").css("display","block");
        	//$("#agenda-holder").css("left", "-" + $("#agenda-holder .dag-" + start).position().left + "px");
    } else {
		var dayWidth = Math.floor(950 / numDays);
        $("#calendar-container").css("display", "block");
        $("#agenda-container").css("display", "none");
		$("#locatie_selector_container").css("display","none");

        var dayWidth = Math.floor($("#calendar-holder").width() / (numDays));
        $("#calendar .dag-th").css("width", (dayWidth-1) + "px");
        $("#calendar .overviewtable").css("width", ((dayWidth - 1) * (totalDays) - 1) + "px");
        //$("#calendar").css("left", "-" + $("#calendar .dag-" + start).position().left + "px");
    }
	moveAgendacontainer();
}

function moveAgendacontainer(){
	var start = getDaysFromLeft();
	var numDays = getNumSelectDays();
	if (numDays <= maxDayView) {
		$("#agenda-holder").css("left", "-" + $("#agenda-holder .dag-" + start).position().left + "px");
	} else {
		$("#calendar").css("left", "-" + $("#calendar .dag-" + start).position().left + "px");
	}
}

//Fill the agenda with all items
function fillAgenda(msg) {
    $(msg.d).each(
        function() {
            var img = document.createElement("img");
            img.setAttribute("src", this.Image);
            //img.setAttribute("src", "images/voorstelling_thumb.jpg");

            var image = document.createElement("div");
            $(image).addClass("image");
            //$(image).css("height", "52px");
            image.appendChild(img);

            var genre = document.createElement("div");
            fillGenres(genre, this.GenreList);
            $(genre).css("height", "10px");

            var visual = document.createElement("div")
            $(visual).addClass("visual");
            visual.appendChild(image);
            visual.appendChild(genre);

            var tijd = document.createElement("div");
            $(tijd).addClass("tijd");
            tijd.appendChild(document.createTextNode(this.Tijd));

            var location = document.createElement("div");
            $(location).addClass("location").addClass(this.LocatieCode); ;
            location.appendChild(document.createTextNode(this.Locatie));

            var title = document.createElement("h2");
            title.appendChild(document.createTextNode(this.Titel + " "));

            if (this.Uitvoerende != "") {
                var uitvoerende = document.createElement("p");
                $(uitvoerende).addClass("uitvoerende");
                uitvoerende.appendChild(document.createTextNode(this.Uitvoerende));
            }

            var USP = document.createElement("p");
            $(USP).addClass("usp");
            USP.appendChild(document.createTextNode(this.USP));

            var text = document.createElement("div")
            $(text).addClass("text");
            text.appendChild(tijd);
            text.appendChild(location);
            text.appendChild(title);
            text.appendChild(document.createTextNode(" "));
            if (this.Uitvoerende != "") {
                text.appendChild(uitvoerende);
            }
            text.appendChild(USP);

            var enlarge = document.createElement("div");

            $.data($(enlarge).get(0), "uitvoering", this.UitvoeringID);
            $(enlarge).addClass("enlarge");

            if (this.ShowMyHF) {
                var addToMyHF = document.createElement("a");
                $(addToMyHF).addClass("btn btn_add");

                if (isEnglish)
                    addToMyHF.appendChild(document.createTextNode("add to MyHF"));
                else
                    addToMyHF.appendChild(document.createTextNode("naar mijn HF"));

                $(addToMyHF).click(function(e) {
                    value = $.data($(enlarge).get(0), "uitvoering");
                    plaatsBookmark(value, true, "");
                });
            }
            
            var meerinfo = document.createElement("a");
            $(meerinfo).addClass("btn btn_more");

            if (isEnglish)
                meerinfo.appendChild(document.createTextNode("More info"));
            else
                meerinfo.appendChild(document.createTextNode("Meer info"));
            $(meerinfo).click(function(e) {
                value = $.data($(enlarge).get(0), "uitvoering");
                showDetailPopup(value)
            }
            );

            enlarge.appendChild(meerinfo);
            
            if (this.ShowMyHF)
                enlarge.appendChild(addToMyHF);

            var uitvoering = document.createElement("div");
            $(uitvoering).addClass("uitvoering");
            if (this.IsHighlight)
                $(uitvoering).addClass("hf-highlight");

            $(uitvoering).addClass("status-" + this.StatusID);

            $(uitvoering).attr("uitvoeringid", this.UitvoeringID);
            $(uitvoering).attr("id", "uitvoeringID-" + this.UitvoeringID);

            uitvoering.appendChild(visual);
            uitvoering.appendChild(text);
            uitvoering.appendChild(enlarge);

            $("#" + this.TDID).append(uitvoering);
        }
    );


    var one_day = 1000 * 60 * 60 * 24
    var today = new Date();
    var skipDays = Math.ceil((today.getTime() - startDateAgenda.getTime()) / (one_day)) - 1;

    if (skipDays > totalDays || skipDays < 0)
        skipDays = 0;
    
    if (skipDays + 7 > totalDays)
        skipDays = totalDays - 6;
    
    if (skipDays > 2)
        skipDays = skipDays - 2;

    setDayWidth(7, skipDays);
	
	highlightQuery();
	addHighlights();
	
	$("#agenda-holder table.overviewtable div.uitvoering div.enlarge, #mijnHFcontainer div.uitvoering div.enlarge").hover(
		function () {
			$(this).addClass("showEnlarge");
			
		}, 
		function () {
			$(this).removeClass("showEnlarge");
		}
	);
	
	//finished!
	$("#spinner").hide('fast');
}
function addHighlights(){
	
	highlightstar = "<div class='highlightstar' title='Highlight'></div>"
	$(".uitvoering.hf-highlight").find(".genre").append(highlightstar);
	$(".genre.hf-highlight").append(highlightstar);
}
function fillGenres(div, genreList) {
	
    $(div).addClass("genre");
	//div.appendChild(document.createTextNode("."));
	var genretablestart = "<table><tr>";
	var genretableend = "</tr></table>";
    
    for (i = 0; i < genreList.length; i++) {
       // var genrecel = "<td class=\"g-"+genreList[i].GenreID)+"\">.</td>";
		var genrecel = "<td class=\"g-"+genreList[i].GenreID+"\" style=\"background-color:"+genreList[i].Color+"\"></td>";
		var genretablestart = genretablestart + genrecel;
		//$(div).addClass("g-" + genreList[i].GenreID);
//
//        var td = document.createElement("td");
//		 td.appendChild(document.createTextNode("."));
//
//        $(td).css("background-color",genreList[i].Color);
//        tr.appendChild(td);
    }
    var genretable = genretablestart + genretableend;
    //var table = document.createElement("table");
    // table.appendChild(tr);
    //$(div).append(table);
    $(div).append(genretable);
}

// Fill the total overview in the calendar
function fillCalendar(msg) {
    $(msg.d).each(
        function() {
            var blokje = document.createElement("div");
            fillGenres(blokje, this.GenreList);
            if (this.IsHighlight)
                $(blokje).addClass("hf-highlight");
            $(blokje).addClass("status-" + this.StatusID); 
                
            $(blokje).attr("uitvoeringid", this.UitvoeringID);
            $.data($(blokje).get(0), "uitvoering", this.UitvoeringID);
            $(blokje).click(function(e) {
                value = $.data($(blokje).get(0), "uitvoering");
                showDetailPopup(value);
            });
            $("#" + this.TDID).append(blokje);
        }
    );

    $("#calendar .overviewtable tbody tr").each(
        function() {
            curClass = $(this).attr("class");
            $("#locationlist li." + curClass).css("height", $("tr." + curClass).height() - 1 + "px");	
        }
    );

    if ($.browser.msie == true) { 
	    //strange bug in IE with last location in #locationlist
		$("#locationlist li:last").css("height", $("#locationlist li:last").height() -1 +"px");
    }
	
    $("#calendar div.genre").tooltip({
        track: true,
        //left: -210,
        bodyHandler: function() {
            var uitvoering = $.data(this, "uitvoering")
            var infoDiv = $("#uitvoeringID-" + uitvoering).clone();
            return infoDiv;
        }
    });
	//$("#spinner").hide('fast');
}

//place the received season in the calendar
function buildDays(msg) {
    var dagen = msg.d.Dagen;
	var locaties = msg.d.Locaties;
	
	var calendarTheadtr = document.createElement("tr");
	var calendarTbody = document.createElement("tbody");
	
	var agendaTheadtr = document.createElement("tr");
	var agendaTbodyTr = document.createElement("tr");

	var balkDagen = document.createDocumentFragment();
	var locatieUL = document.createDocumentFragment();

	startDateAgenda = eval('new' + msg.d.StartDatum.replace(/\//g, ' '));
    
    totalDays = dagen.length + 1;

    initialDayWidth = Math.floor($("#calendar-container").width() / totalDays);

	for (i = 0; i < dagen.length; i++) {

	    var balkDag = document.createElement("div");
	    balkDag.attributes.setNamedItem
	    $(balkDag).css("width", initialDayWidth + "px").addClass("balkdag");

	    var dagNaam = document.createElement("span");
	    {
	        dagNaam.appendChild(document.createTextNode(dagen[i].DagKort));
	        balkDag.appendChild(dagNaam);
	    }

	    var dagNummer = document.createElement("div");
	    {
	        dagNummer.appendChild(document.createTextNode(dagen[i].Dag));
	        balkDag.appendChild(dagNummer);
	    }
        balkDagen.appendChild(balkDag);
        
        var calendarTh = document.createElement("th");
        {
            $(calendarTh).addClass("dag-th");
            calendarTh.appendChild(document.createTextNode(dagen[i].Dag));
            calendarTheadtr.appendChild(calendarTh);
        }

        var agendaTh = document.createElement("th");
        {
            $(agendaTh).addClass("dag-th");
            agendaTh.appendChild(document.createTextNode(dagen[i].DagKort + " " + dagen[i].Dag + " " + dagen[i].MaandLang));
            agendaTheadtr.appendChild(agendaTh);
        }

        var agendaTd = document.createElement("td");
        {
            $(agendaTd).addClass("agendadag dag-" + i);
            agendaTd.setAttribute("id", "dag-" + dagen[i].Dag + dagen[i].Maand);
            agendaTbodyTr.appendChild(agendaTd);
        }
    }

    for (i = 0; i < locaties.length; i++) {
        var locatieLi = document.createElement("li");
        locatieLi.appendChild(document.createTextNode(locaties[i].Naam));
        $(locatieLi).addClass("loc-" + locaties[i].ID);
        
        locatieUL.appendChild(locatieLi);
        
        var tr = document.createElement("tr");
        $(tr).addClass("loc-" + locaties[i].ID);

        for (j = 0; j < dagen.length; j++) {
            var td = document.createElement("td");
            $(td).addClass("dag-" + j);
            td.setAttribute("id", "dag" + locaties[i].ID + "-" + dagen[j].Dag + dagen[j].Maand);
            tr.appendChild(td);
		}
		
		calendarTbody.appendChild(tr);
	}

	var calendarThead = document.createElement("thead");
	calendarThead.appendChild(calendarTheadtr);

	var calendarTable = document.createElement("table");
	$(calendarTable).addClass("overviewtable");
	calendarTable.appendChild(calendarThead);
	calendarTable.appendChild(calendarTbody);

	var agendaThead = document.createElement("thead");
	agendaThead.appendChild(agendaTheadtr);

	var agendaTbody = document.createElement("tbody");
	agendaTbody.appendChild(agendaTbodyTr);
	
	var agendaTable = document.createElement("table");
	$(agendaTable).addClass("overviewtable");
	agendaTable.appendChild(agendaThead);
	agendaTable.appendChild(agendaTbody);
	
	$("#balk").append(balkDagen);
	$("#calendar").append(calendarTable);
	$("#agenda-holder").append(agendaTable);
	$("#locationlist ul").append(locatieUL);

	initialDayWidth = initialDayWidth + 1;
	
    $.ajax({
        type: "POST",
        url: "Services/agenda.asmx/GetAllCalendar",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: fillCalendar
    });
    
    initAgenda();
}

function getDaysFromLeft() {
    var sliderLeft = $(slider).position().left;
    var start = Math.floor(sliderLeft / initialDayWidth);
    return start;
}

function getNumSelectDays() {
    return Math.floor($(slider).width() / initialDayWidth);
}


