﻿//var currentPanel = null;
$(function () {
	window_OnLoad();
	$("#accordion").accordion({
		fillSpace: false
	});
});

$(window).resize(function () {
	window_OnLoad();

	$("#accordion").accordion("resize");
});

function window_OnLoad(response) {
	
	// Initialise the top navigation menu
	topNavigation_Init();
	// Initialise the Image Slider in header of website
	imageSlider_Init();

		
}

function topNavigation_Init() {    
	// Initialise the top navigation menu
	$("ul.subnav").parent().append("<span></span>"); //Only shows drop down trigger when js is enabled (Adds empty span tag after ul.subnav*)

	$("ul.topnav li span").click(function () { //When trigger is clicked...

		//Following events are applied to the subnav itself (moving subnav up and down)
		$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on click

		$(this).parent().hover(function () {
		}, function () {
			$(this).parent().find("ul.subnav").slideUp('slow'); //When the mouse hovers out of the subnav, move it back up
		});

		//Following events are applied to the trigger (Hover events for the trigger)
	}).hover(function () {
		$(this).addClass("subhover"); //On hover over, add class "subhover"
	}, function () {	//On Hover Out
		$(this).removeClass("subhover"); //On hover out, remove class "subhover"
	});

	
}

function imageSlider_Init() {
	// Initialise the Image Slider in header of website
	$(".imgSlider").resize({
		maxWidth: 682
	});
}

// scripts used by the events calendar
function padDigits(n, totalDigits) {
	n = n.toString();
	var pd = '';
	if (totalDigits > n.length) {
		for (i = 0; i < (totalDigits - n.length); i++) {
			pd += '0';
		}
	}
	return pd + n.toString();
}

function ajax_OnBegin(response) {
	$(".loadingDiv").show();
}

function ajax_OnSuccess(response) {
	window_OnLoad(response);
	$(".loadingDiv").hide();
}

function ajax_OnFailure(response) {
	$(".loadingDiv").hide();
	$("#ContentRight").html(response.get_response().get_responseData());
}

$.dynamicAjax = function (settings) {
	$(".loadingDiv").show();

	var internalSettings = {};
	for (var setting in settings) {
		internalSettings[setting] = settings[setting];
	}

	internalSettings.success = function (data, textStatus, xmlHttpRequest) {
		if (settings.success != null)
			settings.success(data, textStatus, xmlHttpRequest);

		$(".loadingDiv").hide();
	};

	internalSettings.error = function (xmlHttpRequest, error) {
		if (settings.error != null)
			settings.error(xmlHttpRequest, error);

		$(".loadingDiv").hide();
		alert(xmlHttpRequest.responseText);
	};

	return $.ajax(internalSettings);
};

function doMainLayout(elementID, dialogHeight) {
	try {
		if (dialogHeight != null && dialogHeight.length > 0) {
			$(elementID).height(dialogHeight);
		}
		else {
			var newHeight = $(window).height() - $(elementID).offset().top - 34 + "px";
			$(elementID).height(newHeight);
		}

		$(elementID).layout({
			north__resizable: false,
			north__closable: false,
			south__size: 100,
			center__onresize: function () { $(elementID + " .flexigrid .bDiv").height($(elementID + " div.ui-layout-center").innerHeight() - 83); }
		});
	}
	catch (Exception) { }
}

function openDialog(url, dialogTitle, isAuthenticated, width) {	
	if (isAuthenticated == "True") {
		$(".loadingDiv").show();

		$('#modalDialog').html("");

		$('#modalDialog').dialog({ title: dialogTitle });
		$('#modalDialog').dialog('open');
		$('#modalDialog').load(url, function () {
			initializeForm("#popupLayoutPanel", "#popupLayoutPanel", width == null ? "550px" : width);

			$("#modalDialog").trigger("page_OnLoad", [$('#modalDialog'), null]);
			$("#modalDialog").unbind("page_OnLoad");
		});
	}
}

function initializeForm(parentPanel, layoutPanelID, layoutPanelSize) {
	doMainLayout(layoutPanelID, layoutPanelSize);
	
	$(".datetimepicker").datetimepicker({
		dateFormat: 'yy-mm-dd',
		timeFormat: 'hh:mm',		
		buttonImage: '/content/images/calendar.png',
		showOn: 'button',
		buttonImageOnly: true
	});

//	$("#saveButton").click(function () {
//		$(".loadingDiv").show();
//		$("#editForm").submit();
//	});

	$("#saveEventButton").click(function () {
		var isValid = $('#editForm').valid();	
		if (isValid) { 
			$(".loadingDiv").show();
			$("#editForm").submit();
		}
		
	});

	$("#saveLinkButton").click(function () {
		var isValid = $('#editFormLink').valid();
		if (isValid) {
			$(".loadingDiv").show();
			$("#editFormLink").submit();
		}
	});

	$("#saveDocButton").click(function () {
		var isValid = $('#editFormDoc').valid();
		if (isValid) {
			$(".loadingDiv").show();
			$("#editFormDoc").submit();
		}
	});

//	$("#saveNewsletterButton").click(function () {
//		var isValid = $('#editFormDoc').valid();
//		if (isValid) {
//			$(".loadingDiv").show();
//			$("#editFormDoc").submit();
//		}
//	});

	$(parentPanel + " #deleteButton").click(function () {
		if (confirm("Are you sure you want to delete this entry?")) {
			var action = $(parentPanel + " #editForm").attr("action");

			var formElements = action.split("/");

			var action = "";

			for (var i = 1; i < formElements.length; i++) {
				if (formElements[i].indexOf("?") < 1 && formElements[i] != parseInt(formElements[i]))
					action = action + "/" + formElements[i]
				else
					break;

			}

			action = action + "/Delete/" + $("#editForm #Id").attr("value");

			$.dynamicAjax({
				url: action,
				success: function (data) {
					if (data == "OK") {
						if ($("#modalDialog").html().length > 0) {
							$("#modalDialog").dialog("close");
							$('#modalDialog').html("");
							CalendarListReload();
						}
						else {
							alert(data);
						}
					}
					else {
						alert(data);
					}
				},
				error: function (jqXhr, textStatus, errorThrown) {
					alert("Error '" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
				},
				complete: function () {
					$(".loadingDiv").hide();
				}

			});
		}
	});

	$(".loadingDiv").hide();

	$.validator.unobtrusive.parse(parentPanel + " #editForm");
	$.validator.unobtrusive.parse(parentPanel + " #editFormLink");
	$.validator.unobtrusive.parse(parentPanel + " #editFormDoc");	
	
}

function editForm_OnFailure(sender, eventArgs) {
	$(".loadingDiv").hide();
	//alert(sender.status + ' ' + sender.statusText);
}

function editForm_OnBegin(sender, eventArgs) {
	$(".loadingDiv").show();
}

function editForm_OnComplete(sender, eventArgs) {
	$(".loadingDiv").hide();

	if (sender.responseText == "OK") {
		if ($("#modalDialog").html().length > 0) {
			$("#modalDialog").dialog("close");
			$('#modalDialog').html("");
			CalendarListReload();
			
		}
	}
	else
		//alert(sender.responseText);
		CalendarReload();
}


// ================= Functions for Events Calendar ===========================

function GetTotalDays(date) {
	var m = date.getMonth() + 1;
	if (date == 2) return 29;
	if (m != 1 && m != 3 && m != 5 && m != 7 && m != 8 && m != 10 && m != 12) return 30;
	else
		return 31;
}

function calendar_OnEventClick(id, title) {
	openDialog('/Calendar/Event/'+id, title, "True");
}


function CalendarReload() {
	$('#calendar').fullCalendar("destroy");
	InitCalendar();
}

function CalendarListReload() {
	$.dynamicAjax({
		url: '/Calendar/EventList',
		success: function (data) {
			$('#ContentRight').html(data);
		}
	});		
}

function InitCalendar() {
	var date = new Date();
	var d = date.getDate();
	var m = date.getMonth();
	var y = date.getFullYear();
	var firstDay = padDigits(y, 4) + '-' + padDigits(m + 1, 2) + '-' + padDigits(1, 2);
	var lastDay = padDigits(y, 4) + '-' + padDigits(m + 1, 2) + '-' + padDigits(GetTotalDays(date), 2);
	var hostCR = $('#ContentRight').context.URL;
	var host = $('#Wrap').context.URL;
	var s = new Date(y, m + 1, 1);
	var e = new Date(y, m + 1, 30);
	var eventList = new Array();	

	$.dynamicAjax({
		url: '/Calendar/GetAllEvents',
		success: function (data) {
			eventList = data;
			$('#calendar').fullCalendar({
				selectable: true,
				selectHelper: true,
				editable: true,
				events: eventList,
				eventClick: function (calEvent, jsEvent, view) {
					calendar_OnEventClick(calEvent, jsEvent, view);
				},
				dayClick: function (date, allDay, jsEvent, view) {
					createEvent(date, allDay, jsEvent, view);
				},
				gotoDate: function (date) {
					calendar_gotodate(date);
				}
			});
		}
	});

}


function eventMenu_OnEventClick(id, title) {
	openDialog('/Calendar/Event/' + id, title, "True");
}



