﻿/// <reference name="MicrosoftAjax.js" />
/// <reference name="Util.js" />
/// <reference path="../GlobalJSFunctionsDetail.js" />

// Will be removed.
var liveeditId = 0;

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;

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);
}

// Will be removed.
function showLiveEditControl(id, elementID) {
	document.getElementById('LiveEditControl' + id).style.display = 'block';
	showToolTip2(id, elementID);
}

// Will be removed.
function hideLiveEditMenuCategory(sender, event, id, elementID, control) {
	var temp = document.getElementById(elementID);
	if (temp) {
		temp.style.zIndex = 0;
		var divID = document.getElementById(id.replace('_', ''));
		if (divID)
			divID.style.position = '';
	}
	hideLiveEditMenu(sender, event, id, control, 1, 0);
}

// Will be removed.
function hideLiveEditMenu(sender, event, id, control, isCategory, elementID) {
	var toElement = (event.toElement ? event.toElement : event.relatedTarget);

	if (toElement) {
		while (toElement.parentNode != null) {
			if (toElement == sender)
				return;
			toElement = toElement.parentNode;
		}
	}

	document.getElementById('LiveEditMoreActions' + id).style.display = 'none';

	if (showToolTip) {
		var temp = document.getElementById('LiveEditToolTip' + id);
		if (temp)
			temp.style.display = 'none';
	}

	if (control)
		document.getElementById('LiveEditControl' + id).style.display = 'none';

	document.getElementById('LiveEditControl' + id).style.width = 'auto';
	if (!isCategory) {
		var item = document.getElementById(elementID);
		if (item)
			item.style.zIndex = 0;
	}
}

// Will be removed.
function showToolTip2(id, elementID) {
	if (showToolTip) {
		var temp = document.getElementById('LiveEditToolTip' + id);
		if (temp)
			temp.style.display = 'block';
	}

	if (document.getElementById(elementID)) {
		document.getElementById(elementID).style.zIndex = 2;
		if (elementID.substring(0, 3) == "cat" && document.getElementById(id)) {
			document.getElementById(id).style.position = 'relative';
			document.getElementById(id).style.zIndex = 0;
		}
	}
}

// Will be removed, see new code at bottom of file.
function moreActionsCategory(liveEditControlIDSuffix, catElemID) {
	var temp = document.getElementById(catElemID);
	if (temp)
		temp.style.zIndex = 2;
	moreActions(liveEditControlIDSuffix);
}

// Will be removed, see new code at bottom of file.
function moreActions(liveEditControlIDSuffix) {

	if (showToolTip) {
		var tooltipdiv = document.getElementById('LiveEditToolTip' + liveEditControlIDSuffix);

		if (tooltipdiv)
			tooltipdiv.style.display = 'none';

		showToolTip = false;
		document.cookie = "showToolTip=false;";
	}

	if (liveeditId != 0 && liveeditId != liveEditControlIDSuffix && document.getElementById('LiveEditMoreActions' + liveeditId)) {
		document.getElementById('LiveEditMoreActions' + liveeditId).style.display = 'none';
	}

	var actions = document.getElementById('LiveEditMoreActions' + liveEditControlIDSuffix);

	if (actions.style.display == 'none') {
		var liveEditControl = document.getElementById('LiveEditControl' + liveEditControlIDSuffix);

		//hack for Z-index issue in IE
		liveEditControl.style.position = 'relative';
		liveEditControl.style.position = 'absolute';

		liveEditControl.style.width = '400px';
		actions.style.display = 'block';
	}
	else {
		actions.style.display = 'none';
	}

	liveeditId = liveEditControlIDSuffix;
}

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';
	}
		
	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, '');
	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.strActionFE.value = "CivicAlertItemPublish";
			}
			else
				frmBAF.strActionFE.value = "CivicAlertItemSave";
			break;
		case 'blog':
			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;
	}
	window.parent.raiseAsyncPostback(updatePanelID, ItemId, 1);
}
function sendEmailFE(frmFQP, ysnRadioButtonSelected, from, ItemId, UpdatePanelId, draftPublish) {
	if (frmFQP == 'frmBlogItemForm' || frmFQP == 'frmAlertInfo') {
		var frmFQF = document.getElementById(frmFQP);
		var frmEmail = document.getElementById(frmFQP);

	}
	else {
		var frmFQF = window.parent.document.getElementById(frmFQP);
		var frmEmail = document.frmSendEmail;

	}
	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;
	}
}

// TODO: Uhhhhhh... parseInt() does not throw exceptions!
function validNumber(num) {
	var tmp = num;
	try { tmp = parseInt(tmp); }
	catch (ex) { return false; }
	if (tmp != num)
		return false;
	return true;
}

// ==== NEW CODE BELOW =====
// TODO: Document what this stuff does. Arguments, methods, etc.

function elemInsideOrEq(elemFirst, elemSecond) {
	/// <summary>Gets whether or not second element specified is inside or is equal to first element.</summary>
	/// <param name="elemFirst" type="domElement">First element.</param>
	/// <param name="elemSecond" type="domElement">Second element.</param>
	if (elemFirst == elemSecond)
		return true;

	if (elemFirst && elemSecond) {
		elemSecond = elemSecond.parentNode;

		while (elemSecond != null) {
			if (elemSecond == elemFirst)
				return true;

			elemSecond = elemSecond.parentNode;
		}
	}

	return false;
}

function hookAnchorClick(anchor, fn) {
	/// <summary>Hooks an anchor onclick and prevents default HREF behavior.</summary>
	/// <param name="anchor" type="domElement">The DOM element to attach the event handler for.</param>
	/// <param name="fn" type="Function">Function to be called when anchor is clicked. Should have sender and event argument, in that order.</param>
	var clickHandler = function(event) {
		var sender;

		if (window.event) {
			event = window.event;
			sender = event.srcElement;
		}
		else
			sender = event.target;

		fn(sender, event);

		if (event.stopPropagation)
			event.stopPropagation();
		else
			event.cancelBubble = true;

		return false;
	}

	// HACK: MSIE/Opera onclick fails to operate correctly.
	if (isie7 || isie6 || (document.documentMode < 8) || window.opera)
		anchor.onmousedown = clickHandler;
	else
		anchor.onclick = clickHandler;
}

// 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);
}