var renderType = "calendar";

var selectedDay = null;
var selectedEvent = null;

var filter = "all";

var month = null;
var year = null;

var weekStart = 0;

var container = null;
var calendarXSLT = null;
var listXSLT = null;

var itemEditXSLT = null;
var itemViewXSLT = null;

var timeOffTypesXML = null;
var minutesXML = null;
var hoursXML = null;
var ampmXML = null;

var httpRequest = null;

var calendarData = null;
var monthData = null;

var monthesList = null;
var yearsList = null;

var itemTypesXML = null;

var captionEditXSLT = null;

function calendarOnLoad() {
	httpRequest = new xml_http_request();
	var currentDate = new Date();
	month = currentDate.getMonth()+1;
	year = (currentDate.getYear()<1900 ? currentDate.getYear()+1900 : currentDate.getYear());

	calendarData = new Array();
	monthData = new Array();

	monthesList = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

	yearsList = new Array();
	var j=0;
	for(var i=year-3;i<=year+3;i++) {
		yearsList[j] = i;
		j++;
	}
	container = document.getElementById("container");
	
	itemTypesXML = loadXMLByAction("calendarTypesXML");
	renderCalendar();

}

function renderCalendar() {
	switch(renderType) {
		case "calendar":
			_renderCalendar();
			break;
		case "list":
			_renderList();
			break;
	}
}

function _renderCalendar() {
	var xmlData = null;

	if(calendarXSLT==null) {calendarXSLT = loadXMLByAction("calendar_xslt");}
	if(calendarData[year] == undefined) {calendarData[year] = new Array();}
	if(calendarData[year][month] == undefined) {calendarData[year][month] = loadXMLByAction("calendar_xml&year="+year+"&month="+month+"&weekStart="+weekStart);}

	if(monthData[year] == undefined) {monthData[year] = new Array();}
	if(monthData[year][month] == undefined) {monthData[year][month] = loadXMLByAction("month_xml&year="+year+"&month="+month+"&weekStart="+weekStart);}

	xmlData = string2xml("<data></data>");
	xmlData.selectSingleNode("//data").appendChild(monthData[year][month].selectSingleNode("//list/weeks").cloneNode(true));
	xmlData.selectSingleNode("//data").appendChild(monthData[year][month].selectSingleNode("//list/weekDays").cloneNode(true));
	xmlData.selectSingleNode("//data").appendChild(calendarData[year][month].selectSingleNode("//list/items").cloneNode(true));
	xmlData.selectSingleNode("//data").appendChild(itemTypesXML.selectSingleNode("//types").cloneNode(true));
		
	xmlData.selectSingleNode("//data").appendChild(xmlData.createElement("monthes"));
	for(var i=0;i<monthesList.length;i++) {
		var monthEl = xmlData.createElement("month");
		monthEl.setAttribute("number", i+1);
		monthEl.setAttribute("caption", monthesList[i]);
		xmlData.selectSingleNode("//data/monthes").appendChild(monthEl);
	}

	xmlData.selectSingleNode("//data").appendChild(xmlData.createElement("years"));
	for(var i=0;i<yearsList.length;i++) {
		var yearEl = xmlData.createElement("year");
		yearEl.setAttribute("number", yearsList[i]);
		yearEl.setAttribute("caption", yearsList[i]);
		xmlData.selectSingleNode("//data/years").appendChild(yearEl);
	}

	var params = new Array();
	params["access"] = access;

	params["filter"] = filter;

	params["month"] = month;
	params["monthName"] = monthesList[month-1];
	params["year"] = year;
	params["weekStart"] = weekStart;
//debug(xml2string(xmlData));
	xslt_transform(xmlData, calendarXSLT, container, params);

	DynarchMenu.setup('contextMenu', { context: true });
//debug(xml2string(xmlData));
}

function _renderList() {
	var xmlData = null;
	var params = new Array();
	if(listXSLT==null) {listXSLT = loadXMLByAction("list_xslt");}
	if(calendarData[year] == undefined) {calendarData[year] = new Array();}
	if(calendarData[year][month] == undefined) {calendarData[year][month] = loadXMLByAction("calendar_xml&year="+year+"&month="+month+"&weekStart="+weekStart);}

	if(monthData[year] == undefined) {monthData[year] = new Array();}
	if(monthData[year][month] == undefined) {monthData[year][month] = loadXMLByAction("month_xml&year="+year+"&month="+month+"&weekStart="+weekStart);}

	xmlData = string2xml("<data></data>");
	xmlData.selectSingleNode("//data").appendChild(monthData[year][month].selectSingleNode("//list/weeks").cloneNode(true));
	xmlData.selectSingleNode("//data").appendChild(monthData[year][month].selectSingleNode("//list/weekDays").cloneNode(true));
	xmlData.selectSingleNode("//data").appendChild(calendarData[year][month].selectSingleNode("//list/items").cloneNode(true));
	xmlData.selectSingleNode("//data").appendChild(itemTypesXML.selectSingleNode("//types").cloneNode(true));

	xmlData.selectSingleNode("//data").appendChild(xmlData.createElement("monthes"));
	for(var i=0;i<monthesList.length;i++) {
		var monthEl = xmlData.createElement("month");
		monthEl.setAttribute("number", i+1);
		monthEl.setAttribute("caption", monthesList[i]);
		xmlData.selectSingleNode("//data/monthes").appendChild(monthEl);
	}

	xmlData.selectSingleNode("//data").appendChild(xmlData.createElement("years"));
	for(var i=0;i<yearsList.length;i++) {
		var yearEl = xmlData.createElement("year");
		yearEl.setAttribute("number", yearsList[i]);
		yearEl.setAttribute("caption", yearsList[i]);
		xmlData.selectSingleNode("//data/years").appendChild(yearEl);
	}

	params["access"] = access;

	params["filter"] = filter;
	params["month"] = month;
	params["monthName"] = monthesList[month-1];
	params["year"] = year;
	params["weekStart"] = weekStart;

	xslt_transform(xmlData, listXSLT, container, params);

	DynarchMenu.setup('contextMenu', { context: true });
//debug(xml2string(xmlData));
}

function setMonth(m) {
	month = parseInt(m);
	renderCalendar();	
}

function setYear(y) {
	year = parseInt(y);
	renderCalendar();	
}

function gotoMonth(rel) {
	month+=rel;
	if(month>12) {
		year++;
		month = month-12;
	}
	if(month<1) {
		year--;
		month = 12+month;
	}
	renderCalendar();
}

function addItem(type) {
//alert(type);
	var popupEl = document.getElementById("popupDiv");
	if(itemEditXSLT==null) {itemEditXSLT = loadXMLByAction("item_edit_xslt");}

	if(hoursXML==null) {hoursXML=loadXMLByAction("hours_list");}
	if(minutesXML==null) {minutesXML=loadXMLByAction("minutes_list");}	if(ampmXML==null) {ampmXML=loadXMLByAction("ampm_list");}

	//if(timeOffTypesXML==null) {timeOffTypesXML = loadXMLByAction("time_off_types_list");}

	var xml = string2xml("<data></data>");

	var itemText = "<item>\n";
	itemText += "<citem_id></citem_id>\n";
	itemText += "<type>"+type+"</type>\n";
	itemText += "<date>"+selectedDay.month+"/"+selectedDay.day+"/"+year+"</date>\n";
	itemText += "<dateF>"+selectedDay.month+"/"+selectedDay.day+"/"+year+"</dateF>\n";
	itemText+="</item>\n";
	
	var itemXML = string2xml(itemText);

	xml.selectSingleNode("//data").appendChild(itemXML.selectSingleNode("//item").cloneNode(true));
	//xml.selectSingleNode("//data").appendChild(timeOffTypesXML.selectSingleNode("//time_off_types_list").cloneNode(true));
	xml.selectSingleNode("//data").appendChild(itemTypesXML.selectSingleNode("//types").cloneNode(true));
	
	xml.selectSingleNode("//data").appendChild(hoursXML.selectSingleNode("//hours_list").cloneNode(true));
	xml.selectSingleNode("//data").appendChild(minutesXML.selectSingleNode("//minutes_list").cloneNode(true));	xml.selectSingleNode("//data").appendChild(ampmXML.selectSingleNode("//ampm_list").cloneNode(true));
	
//alert(xml2string(xml));
//debug(xml2string(xml));
	xslt_transform(xml, itemEditXSLT, popupEl);

	popupEl.style.width = "500px";
	popupEl.style.top = findPosY(selectedDay.el) + selectedDay.el.offsetHeight + 3 + "px";
	popupEl.style.left = "100px";

	popupEl.style.display = "block";

	Calendar.setup(
	{
	inputField : "date", // ID of the input field
	ifFormat : "%m/%d/%Y", // the date format
	button : "setDate", // ID of the button
	electric : false
	}
	);
}

function editItem(type, citem_id) {
	var popupEl = document.getElementById("popupDiv");
	if(itemEditXSLT==null) {itemEditXSLT = loadXMLByAction("item_edit_xslt");}

	if(hoursXML==null) {hoursXML=loadXMLByAction("hours_list");}
	if(minutesXML==null) {minutesXML=loadXMLByAction("minutes_list");}
	if(ampmXML==null) {ampmXML=loadXMLByAction("ampm_list");}

	//if(timeOffTypesXML==null) {timeOffTypesXML = loadXMLByAction("time_off_types_list");}

	var xml = string2xml("<data></data>");

	var itemXML = calendarData[year][month].selectSingleNode("//list/items/item[citem_id = '"+citem_id+"']");//.cloneNode(true);
//alert(xml2string(itemXML));
	xml.selectSingleNode("//data").appendChild(itemXML.selectSingleNode(".").cloneNode(true));
	//xml.selectSingleNode("//data").appendChild(timeOffTypesXML.selectSingleNode("//time_off_types_list").cloneNode(true));
	xml.selectSingleNode("//data").appendChild(itemTypesXML.selectSingleNode("//types").cloneNode(true));
	
	xml.selectSingleNode("//data").appendChild(hoursXML.selectSingleNode("//hours_list").cloneNode(true));
	xml.selectSingleNode("//data").appendChild(minutesXML.selectSingleNode("//minutes_list").cloneNode(true));
	xml.selectSingleNode("//data").appendChild(ampmXML.selectSingleNode("//ampm_list").cloneNode(true));
	
//debug(xml2string(xml));
	xslt_transform(xml, itemEditXSLT, popupEl);

	popupEl.style.width = "500px";
	popupEl.style.top = findPosY(selectedDay.el) + selectedDay.el.offsetHeight + 3 + "px";
	popupEl.style.left = "100px";

	popupEl.style.display = "block";

	Calendar.setup(
	{
	inputField : "date", // ID of the input field
	ifFormat : "%m/%d/%Y", // the date format
	button : "setDate", // ID of the button
	electric : false
	}
	);
}

function viewItem(type, citem_id) {
	var popupEl = document.getElementById("popupDiv");
	if(itemViewXSLT==null) {itemViewXSLT=loadXMLByAction("item_view_xslt");}

	var xml = string2xml("<data></data>");

	var itemXML = calendarData[year][month].selectSingleNode("//list/items/item[citem_id = '"+citem_id+"']").cloneNode(true);

	xml.selectSingleNode("//data").appendChild(itemXML.cloneNode(true));
//alert(xml2string(xml));
	xslt_transform(xml, itemViewXSLT, popupEl);

	popupEl.style.width = "500px";
	popupEl.style.top = findPosY(selectedDay.el) + selectedDay.el.offsetHeight + 3 + "px";
	popupEl.style.left = "100px";

	popupEl.style.display = "block";
}


function saveItem(f) {
	var citem_id = f.citem_id.value;
	var saveRequest = form2string(f);
	var responseXML = loadXMLByAction("save_item&"+saveRequest);
	if(responseXML.selectSingleNode("//row").getAttribute("result") == "ok") {
		if(citem_id == "") {
			calendarData[year][month].selectSingleNode("//list/items").appendChild(responseXML.selectSingleNode("//row/item").cloneNode(true));
		} else {
			calendarData[year][month].selectSingleNode("//list/items").replaceChild(responseXML.selectSingleNode("//row/item").cloneNode(true), calendarData[year][month].selectSingleNode("//list/items/item[citem_id = '"+citem_id+"']"));
		}
		hidePopup();
		renderCalendar();
		alert("Saved OK")
	} else {
		hidePopup();
		alert("Saving Failed");
	}
//debug(xml2string(calendarData[year][month]));
}


function hidePopup(ev) {
	document.getElementById("popupDiv").style.display = "none";
	document.getElementById("popupFrame").style.display = "none";
}

function clearDay() {
	alert("Clear Day "+selectedDay.day);
}

function deleteItem(citem_id) {
	if(confirm("Do you realy want to delete this item?")) {
		var responseXML = loadXMLByAction("delete_item&id="+citem_id);
		if(responseXML.selectSingleNode("//response").firstChild.nodeValue == "ok") {
			calendarData[year][month].selectSingleNode("//list/items").removeChild(calendarData[year][month].selectSingleNode("//list/items/item[citem_id = '"+citem_id+"']"));		
			renderCalendar();
			alert("Deleted OK");
		} else {
			alert("Deleting Failed");
		}
		hidePopup();
	}
}

function editEvent() {
	editItem(selectedEvent.type, selectedEvent.id);
}

function deleteEvent() {
	deleteItem(selectedEvent.id);
}

function viewEvent() {
	viewItem(selectedEvent.type, selectedEvent.id);
}

function viewAs(rt) {
	renderType = rt;
	renderCalendar();
}

function filterBy(val) {
	filter = val;
	renderCalendar();
	document.getElementById("filterTypeSelect").focus();
}

function changeDayCaption() {
	var popupEl = document.getElementById("popupDiv");
	if(captionEditXSLT==null) {captionEditXSLT = loadXMLByAction("caption_edit_xslt");}

	var dayNode = monthData[year][month].selectSingleNode("//list/weeks/*/day[@year='"+year+"' and @month='"+selectedDay.month+"' and @day='"+selectedDay.day+"']");
	
	if(!dayNode) {
		alert("Error Occured");
		return;
	}
	
	var xml = dayNode ? string2xml("<data>"+xml2string(dayNode)+"</data>") : string2xml("<data></data>");

//alert(xml2string(xml));
	xslt_transform(xml, captionEditXSLT, popupEl);

	popupEl.style.width = "500px";
	popupEl.style.top = findPosY(selectedDay.el) + selectedDay.el.offsetHeight + 3 + "px";
	popupEl.style.left = "100px";

	popupEl.style.display = "block";
}

function saveCaption(f) {
	var request = "date="+(f.elements["year"].value + "-" + f.elements["month"].value + "-" + f.elements["day"].value) + "&caption=" + encodeURIComponent(f.elements["caption"].value);
	var responseXML = loadXMLByAction("save_caption&"+request);
	if(responseXML.selectSingleNode("//result").getAttribute("result") == "ok") {
		monthData[year][month].selectSingleNode("//list/weeks/*/day[@year='"+f.elements["year"].value+"' and @month='"+f.elements["month"].value+"' and @day='"+f.elements["day"].value+"']").setAttribute("caption", f.elements["caption"].value);
		hidePopup();
		renderCalendar();
		alert("Saved OK")
	} else {
		hidePopup();
		alert("Saving Failed");
	}
}
