﻿/// <reference name="MicrosoftAjax.js" />
/// <reference name="Util.js" />
/// <reference path="../GlobalJSFunctionsDetail.js" />

var blockMenuSpawn = false;
var showAddDetails = false;
var showToolTip = false;
var showLiveEditControls = false;
var previousKAMControl = null;

var loadOrAjaxUpdate = function() {
	// Allow menu spawning after an AJAX request completes.
	blockMenuSpawn = false;

	// Update cookie caches.
	showAddDetails = getCookieValue('showAddDetails');
	showToolTip = getCookieValue('showToolTip');
	showLiveEditControls = getCookieValue('showLiveEditControls');
	previousKAMControl = null;

	// Force boolean, handle NULL cookies.
	showAddDetails = (showAddDetails == null ? false : (showAddDetails == 'true'));
	showLiveEditControls = (showLiveEditControls == null ? false : (showLiveEditControls == 'true'));
	showToolTip = (showToolTip == null ? true : (showToolTip == 'true'));
}

// Constants below are documented in the enumerations
// present in the CivicPlus.CMS.Library.Common.Enums namespace.

// See this page a good resource on JScript intellisense.
// http://skysanders.net/subtext/archive/2010/02/22/visual-studio-javascript-intellisense-uncovered.aspx

// Status range constants. A status that falls within a range belongs to that range.
// e.g. SUBMITTED is 14, therefore is a DRAFT-type status code.
var MIN_DRAFT = 10;
var MAX_DRAFT = 19;
var MIN_PUBLISHED = 20;
var MAX_PUBLISHED = 40;
var MIN_DELETED = 0;
var MAX_DELETED = 9;

// Specific status constants.
var DRAFT = 10;
var DRAFT_EXPIRED = 11;
var DRAFT_PENDING = 12;
var PUBLISHED = 40;
var PUBLISHED_EXPIRED = 20;
var PUBLISHED_PENDING = 21;
var SUBMITTED = 14;
var REJECTED = 13;

// Rights constants.
var VIEW = 1; // Public
var READONLY = 2; // Admin Interface
var AUTHOR = 3;
var PUBLISHER = 4;
var OWNER = 5;

// Fade-out for live edit menus.
function liveEditHideMenu(elem, callback) {
	elem.style.display = 'none';
	callback();
	return;
	/*
		// Uncomment to introduce fade effect.
		// Method only called in Alert Center currently.
		// Would need to be retroactively added to other modules.

		if (elem.style.display == 'none')
			callback();
		else {
			var elemParentJQ = $(elem.parentNode);
		
			elemParentJQ.fadeOut(300, 'linear', function () {
				elem.style.display = 'none';
				elemParentJQ.fadeTo(1);
				callback();
			});
		}
	*/
}

function cancelFE(needsConfirm) {
	if (!confirm("You will discard any unsaved changes. Do you want to proceed?"))
		return;
	window.parent.closeModalDialog('editItemBehavior');
	return false;
}

function raiseAsyncPostback(updatePanelID, itemID, closePopUp) {
	if (closePopUp)
		closeModalDialog('editItemBehavior');
	__doPostBack(updatePanelID, itemID);
}

function showHideAdditionalDetails(id, minHeight, maxHeight) {
	var item = document.getElementById(id);
	if (item.style.display == 'block') {
		item.style.display = 'none';
		document.getElementById("a_" + id).innerHTML = '&#9658;&nbsp;Show Additional Details';

		showAddDetails = false;
		document.cookie = "showAddDetails=false;";

		window.parent.changeModalDialogHeight(minHeight, 'false');
	}
	else {
		item.style.display = 'block';
		document.getElementById("a_" + id).innerHTML = '&#9660;&nbsp;Hide Additional Details';

		showAddDetails = true;
		document.cookie = "showAddDetails=true;";

		window.parent.changeModalDialogHeight(maxHeight, 'true');
	}
}

function SaveAndSendFE(title, startDate) {
	document.getElementById('AutoNotifyMe').style.display = 'block';
	document.getElementById('itemcontent').style.display = 'none';

	var curDate = new Date();
	if(startDate != '')
		var startDate = new Date(startDate);
	if (startDate > curDate) {
		document.getElementById('pending').style.visibility = 'visible';
		document.getElementById('noPending').style.visibility = 'hidden';
	}
	else {
		document.getElementById('pending').style.visibility = 'hidden';
		document.getElementById('noPending').style.visibility = 'visible';
	}

	if (document.getElementById('ShowSMS').value == "0") {
        document.getElementById('txtMsgMobileLabel').style.visibility = 'hidden';
        document.getElementById('txtMsgMobile').style.visibility = 'hidden';
        document.getElementById('txtMsgMobileCounter').style.visibility = 'hidden';
    }
	else {
	    var elem = document.getElementById(title);
	    if (elem) {
	        document.getElementById('txtMsgMobile').value = elem.value;
	    }
	}
	window.parent.changeModalDialogHeight(310, '');
	return false;
}

function cancelFE(needsConfirm) {
	if (!confirm("You will discard any unsaved changes. Do you want to proceed?"))
		return;
	window.parent.closeModalDialog('editItemBehavior');
	return false;
}

function CancelSaveAndSendFE(height) {
	document.getElementById('AutoNotifyMe').style.display = 'none';
	document.getElementById('itemcontent').style.display = 'block';
	//window.parent.changeModalDialogHeight(height, '');
	window.parent.setModalClassForEditItemBehavior('liveEdit', '');
	return false;
}
//this is a temp fix for calendar because kyle has moved the code to modal.css file and now he is going reference
// each modal by its own name - AK
function CancelSaveAndSendCalendarFE(height) {
	document.getElementById('AutoNotifyMe').style.display = 'none';
	document.getElementById('itemcontent').style.display = 'block';
	//window.parent.changeModalDialogHeight(height, '');
	window.parent.setModalClassForEditItemBehavior('liveEdit calendar', '');
	return false;
}

function publishItemFE(ysnSend, ysnSendAtStart, ysnSendBeforeDays, frmBAF, from, ItemId, updatePanelID, draftPublish) {
	frmBAF.ysnSave.value = 1;
	frmBAF.ysnSend.value = ysnSend;
	frmBAF.ysnSendAtStart.value = ysnSendAtStart;
	frmBAF.ysnSendBeforeDays.value = ysnSendBeforeDays;
	switch (from) {
		case 'civicalerts':
			if (frmBAF.curPage && frmBAF.curPage.value == 'CivicAlertForm') {
				if (draftPublish)
					window.parent.document.getElementsByName('strActionFE')[0].value = "CivicAlertItemPublish";
				else {
					frmBAF.ysnPublishDetail.value = 1;
					frmBAF.submit();
				}
			}
			else
				frmBAF.strActionFE.value = "CivicAlertItemSave";
			break;
		case 'blogs':
			if (frmBAF.curPage && frmBAF.curPage.value == 'BlogItemForm') {
				if (draftPublish)
					window.parent.document.getElementsByName('strActionFE')[0].value = 'BlogItemPublish';
				else
					frmBAF.strActionFE.value = 'BlogItemPublish';
			}
			else
				frmBAF.strActionFE.value = 'BlogItemSave';
			break;
		case 'calendar':
			__doPostBack('ctl07$btnPublishFE', 'OnClick');
			return true;
			break;
	}
	if (from != 'calendar')
		window.parent.raiseAsyncPostback(updatePanelID, ItemId, 1);
}

function sendEmailFE(frmFQP, ysnRadioButtonSelected, from, ItemId, UpdatePanelId, draftPublish) {
	var frmFQF;
	var frmEmail;
	if (frmFQP == 'frmBlogItemForm' || frmFQP == 'frmAlertInfo') {
		frmFQF = document.getElementById(frmFQP);
		frmEmail = document.getElementById(frmFQP);
	}
	else if (from == 'calendar') {
		frmFQF = document.aspnetForm;
		frmEmail = document.getElementById(frmFQP);
	}
	else {
		frmFQF = window.parent.document.getElementById(frmFQP);
		frmEmail = document.frmSendEmail;
	}

	if (document.getElementById('txtMsgMobile'))
	    frmFQF.txtSMSComments.value = document.getElementById('txtMsgMobile').value;
		
	var send;
	if (!ysnRadioButtonSelected)
		publishItemFE(false, false, false, frmFQF, from,ItemId, UpdatePanelId, draftPublish);
	else {
		for (var i = 0; i < frmEmail.one.length; i++) {
			if (frmEmail.one[i].checked) {
				send = frmEmail.one[i].value;
			}
		}
		if (send == "Send") {
			frmFQF.txtComments.value = frmEmail.txtMsgComments.value;
			publishItemFE(true, false, false, frmFQF, from, ItemId, UpdatePanelId, draftPublish);
		}
		else if (send == "SendAtStart") {
			frmFQF.txtComments.value = frmEmail.txtMsgComments.value;
			publishItemFE(false, true, false, frmFQF, from, ItemId, UpdatePanelId, draftPublish);
		}
		else if (send == "SendBeforeDays") {
			var userValue = frmEmail.numDays.value;
			if (validNumber(userValue)) {
				frmFQF.txtComments.value = frmEmail.txtMsgComments.value;
				frmFQF.intSendBeforeDays.value = frmEmail.numDays.value;
				publishItemFE(false, false, true, frmFQF, from, ItemId, UpdatePanelId, draftPublish);
			}
			else if (userValue == '') {
				alert('The number of days before the event was not specified.');
			}
			else {
				alert('An invalid value was entered for the number of days. Please enter a valid value.');
			}
		}
		else
			return false;
	}
}

// ==== NEW CODE BELOW =====
// TODO: Document what this stuff does. Arguments, methods, etc.

// Method exists for MSIE. Finds container to apply z-index changes to.
function resolveLiveEditContainer(liveEditControlElem) {
	var parentContainer = liveEditControlElem.parentNode;

	if (parentContainer) {
		if (parentContainer.parentNode && parentContainer.parentNode.tagName == 'TD' && parentContainer.parentNode.parentNode && parentContainer.parentNode.parentNode.tagName == 'TR') {
			parentContainer = parentContainer.parentNode.parentNode;
		}
	}

	return parentContainer;
}

// Semi-replaces moreActionsCategory()
function liveEditCommonCategory(catElem, toolTipElem, menuElem, liveEditControlElem, insideDiv) {
	if (catElem)
		catElem.style.zIndex = 2;

	liveEditCommonItem(toolTipElem, menuElem, liveEditControlElem,insideDiv,true);
}
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return curleft;
}
// Semi-replaces moreActions()
function liveEditCommonItem(toolTipElem, menuElem, liveEditControlElem, insideDiv, isCategoryMenu) {
	// logic for shifting the KAM menus to left if there isn't space on the right side.
	var moreActionsDiv = document.getElementById(insideDiv);
	//get the element distance from right
	var leftpos = findPos(liveEditControlElem.parentNode);
	if (isCategoryMenu) {
		if (document.body.scrollWidth - leftpos < 132) {
			liveEditControlElem.className = liveEditControlElem.className.replace(/liveEditControl/, 'liveEditControl flipH');
			moreActionsDiv.style.left = moreActionsDiv.style.width - 31 + 'px';
		}
		else {
			liveEditControlElem.className = liveEditControlElem.className.replace(/liveEditControl flipH/, 'liveEditControl');
			moreActionsDiv.style.left = '0px';
		}
	}
	else {
		if (document.body.scrollWidth - leftpos < 327) {
			liveEditControlElem.className = liveEditControlElem.className.replace(/liveEditControl/, 'liveEditControl flipH');
			moreActionsDiv.style.left = moreActionsDiv.style.width - 270 + 'px';
		}
		else {
			liveEditControlElem.className = liveEditControlElem.className.replace(/liveEditControl flipH/, 'liveEditControl');
			moreActionsDiv.style.left = '0px';
		}
	}
	//	logic for shifting the KAM menus to left if there isn't space on the right side ends

	if (showToolTip) {
		if (toolTipElem)
			toolTipElem.style.display = 'none';
		showToolTip = false;
		document.cookie = "showToolTip=false;";
	}

	if (menuElem.style.display == 'none') {
		// HACK: Fix for Z-Index Issue in MSIE.
		liveEditControlElem.style.position = 'relative';
		liveEditControlElem.style.position = 'absolute';
		liveEditControlElem.style.width = '400px';
		menuElem.style.display = 'block';
	}
	else
		menuElem.style.display = 'none';

	liveEditControlElem.appendChild(menuElem);
	liveEditControlElem.appendChild(toolTipElem);
}

function adminGetHelp(helpUrl, newWindow) {
	document.body.style.cursor = "wait";

	var fnGotoURL = null;

	if (newWindow == null || newWindow == true)
		fnGotoURL = function (url) { window.open(url); };
	else
		fnGotoURL = function (url) { location.href = url; };

	$.ajax({
		type: "GET",
		url: "/Admin/GetHelp.ashx?Url=" + encodeURIComponent(helpUrl),
		cache: false,
		dataType: "json",
		error: function (xhr, textStatus, errorThrown) {
			location.href = helpUrl;
		},
		success: function (data, textStatus, xhr) {
			if (data.success) {
				var helpDest = "http://" + data.domain + '/SessionImpart.ashx' +
					'?V=' + encodeURIComponent(data.verify) +
					'&R=' + encodeURIComponent(data.url) +
					'&T=' + encodeURIComponent(data.token);

				fnGotoURL(helpDest);
			}
			else
				fnGotoURL(helpUrl);
		}
	});
}
