﻿// ------------------------------------------------------
// This file contains ONLY generic Beweb Savvy functions
// ------------------------------------------------------


// ------------------------------------------
// For List Pages
// ------------------------------------------

function GoPageNum(PageNum) {
	var form = document.forms["form"]
	form["PageNum"].value = PageNum
	form.submit()
}

function ajaxSave(saveData) {
	alert('ajaxSave incomplete:'+saveData)
}

function ColSortBy(sortFieldName) {
	var form = document.forms["form"]
	if (form["ColSortField"].value == sortFieldName) {
		if (form["ColSortDesc"].value == "1") {
			form["ColSortDesc"].value = "0";
		} else {
			form["ColSortDesc"].value = "1";
		}
	} else {
		form["ColSortField"].value = sortFieldName;
		form["ColSortDesc"].value = "0";
	}
	form.submit()
}

// ------------------------------------------
// For Edit Forms Pages
// ------------------------------------------
//function okToCancel() 
//{
//	if (confirm('Are you sure you want to cancel? Changes will be lost. Press ok to continue, or cancel to do nothing.'))
//	{
//		setFormNotDirty();
//		return true;
//	}
//	return false;
//}
//var formIsDirty = 1
//function setFormNotDirty() {
//	formIsDirty = 0
//}

//function CheckFormNotDirty() {
//	//alert('check')
//	if (formIsDirty == 1) {
//		return 'If you leave this page, any changes will not be saved.'
//	}
//	return		//nothing
//}

//$(document).ready(function () {
//	var sPath = window.location.pathname;
//	var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
//	if (sPage.indexOf("Edit.aspx") > -1)
//	{ 
//		//window.onbeforeunload = CheckFormNotDirty
////		$("#ctl00_BodyContent_AddOrUpdateButton").click(setFormNotDirty());
////		$("#ctl00_BodyContent_aspnetForm #SaveAndRefreshButton").click(setFormNotDirty());
////		$("#ctl00_BodyContent_aspnetForm #DeleteButton").click(setFormNotDirty());
//	}
//});




// ------------------------------------------
// For Rich Text Controls
// ------------------------------------------

function IsZeroParagraphSpacing(sourceElement, sourceWindow) {
	// measure P inside the iframe to see if P tags have zero margins (in which case we convert them to single line break else we convert them to double line breaks)
	var usingZeroParaSpacing = false
	var p = null
	var paragraphElements = sourceElement.getElementsByTagName("p")
	if (paragraphElements && paragraphElements.length > 0) {
		p = paragraphElements[0]
	}
	if (p != null) {
		var marginTop, marginBottom
		if (sourceWindow.getComputedStyle) {
			marginTop = parseInt(sourceWindow.getComputedStyle(p, null).getPropertyValue("margin-top"))
			marginBottom = parseInt(sourceWindow.getComputedStyle(p, null).getPropertyValue("margin-bottom"))
		} else if (p.currentStyle) {
			marginTop = parseInt(p.currentStyle.marginTop)
			marginBottom = parseInt(p.currentStyle.marginBottom)
		} else {
			marginTop = parseInt(p.marginTop)
			marginBottom = parseInt(p.marginBottom)
		}
		if (marginTop == 0 && marginBottom == 0) {
			usingZeroParaSpacing = true
		}
	}
	return usingZeroParaSpacing
}

function CopyHtmlToPlainText(htmlFieldName, plainTextFieldName) {
	// get text version
	var sourceWindow = document.getElementById(htmlFieldName + '_ifr').contentWindow;
	var sourceElement = sourceWindow.document.body;
	var el = document.getElementById("PasteBoard")
	var usingZeroParaSpacing = IsZeroParagraphSpacing(sourceElement, sourceWindow)

	// get text version
	var html = sourceElement.innerHTML;
	html = html.replace(/<LI>/ig, "* ")
	html = html.replace(/<\/LI>/ig, "<br>")
	html = html.replace(/<UL>/ig, "")
	html = html.replace(/<\/UL>/ig, "")
	// put URLs in brackets after any links
	html = html.replace(/<A href=\"mailto:([^\"]*?)\".*?>(.*?)<\/A>/ig, "$2 \($1\)")
	html = html.replace(/<A mce_href=\"mailto:([^\"]*?)\".*?>(.*?)<\/A>/ig, "$2 \($1\)")
	html = html.replace(/<A href=\"([^\"]*?)\".*?>(.*?)<\/A>/ig, "$2 \($1\)")
	html = html.replace(/<A mce_href=\"([^\"]*?)\".*?>(.*?)<\/A>/ig, "$2 \($1\)")
	var txt
	if (el.textContent != undefined) {
		// normalise line breaks
		html = html.replace(/<br><\/P>/ig, "</P>")
		html = html.replace(/\r/ig, "")
		html = html.replace(/\n/ig, "")
		if (usingZeroParaSpacing) {
			html = html.replace(/<\/p>/ig, "</p>\r\n")
		} else {
			html = html.replace(/<\/p>/ig, "</p>\r\n\r\n")
		}
		html = html.replace(/<br>/ig, "<br>\r\n")
		html = html.replace(/<br \/>/ig, "<br />\r\n")
		el.innerHTML = html
		txt = el.textContent;
	} else if (el.innerText != undefined) {
		html = html.replace(/<P>/ig, "")
		if (usingZeroParaSpacing) {
			html = html.replace(/<\/P>/ig, "<br>")
		} else {
			html = html.replace(/<\/P>/ig, "<br><br>")
		}
		el.innerHTML = html
		txt = el.innerText;
	} else {
		alert("Sorry, your browser does not support converting HTML to plain text.")
		return
	}

	document.getElementById(plainTextFieldName).value = txt;
}



// ------------------------------------------
// For Picture Upload/Selector Controls
// ------------------------------------------

function cancelSelectPicture(fieldName) {
	//show upload, swap select and file 'name' fields
	var fileObj = document.getElementById('file_' + fieldName)
	var listBoxDomObj = document.getElementById('select_' + fieldName)

	$(fileObj).show()
	$('#sel_' + fieldName).hide(); // hide server selector
	$('#selsv_' + fieldName).show(500);
	$('#file_' + fieldName).show(500);
	$('#file_' + fieldName).css("display", "");
	$('#filedim_' + fieldName).css("display", "");

	if (fileObj.name.indexOf('svyPicInactive_') != -1) //only swap if not already swapped
	{
			// swap names (of "svyPicInactive_" to the active normal field name)
		var holdname = fileObj.name
		fileObj.name = listBoxDomObj.name;
		listBoxDomObj.name = holdname
	}
}

// when user clicks "select from server"
function handleSelectPicture(servicespath, attachmentPath, fieldName, subfolder) {
	var qs = "";
	var url = servicespath + "GetAttachmentPictures.aspx?subfolder=" + escape(subfolder) + "&rnd=" + Math.random();
	$.ajax({
		type: "GET",
		url: url,
		data: qs,
		success: function (msg) {
			// callback - shows the file selection list
			var obj = $('#select_' + fieldName)
			var res = msg.split('\n')
			obj.data["storedOptions"] = res
			var opt = ""
			for (var sc = 0; sc < res.length - 1; sc++) {
				opt += "<option>" + res[sc] + "</option>"
			}
			obj.html(opt)
			$('#sel_' + fieldName).show(500);
			$('#selsv_' + fieldName).hide(500);
			$('#file_' + fieldName).hide(500);
			$('#filedim_' + fieldName).hide(500);
			//$('#filedim_' + fieldName).css("display", "none");

			// select first image
			//handleImagePreviewSelect(attachmentPath, obj[0], subfolder)
		},
		error: function (msg) {
			alert("add failed 2: " + msg.responseText);
			//prompt('copy this',url+'?'+qs)
		}
	});
}

// when user clicks image name, display the preview
function handleImagePreviewSelect(attachmentPath, listBoxDomObj, subfolder) {
	//hide upload
	//swap 'name' fields with upload id 'file_"+this.name' and select id 'select_"+this.name'
	var fieldName = listBoxDomObj.id.split("_")[1]
	var fileObj = document.getElementById('file_' + fieldName)
	//var fileName = $(listBoxDomObj).val()
	var fileName = listBoxDomObj.options[listBoxDomObj.selectedIndex].text
	if (fileName != null) {
		// show image as a preview
		//$('#pv_'+fieldName).attr('src',attachmentPath+(fileName+'').replace('.','_pv.'))
		var previewImg = $('#pv_' + fieldName)[0]
		pictureSelectorLoadPreview(previewImg, attachmentPath + subfolder + (fileName + ''))

		// set value in case subfolder is different
		//$(listBoxDomObj).val(subfolder + fileName);
		listBoxDomObj.options[listBoxDomObj.selectedIndex].value = subfolder + fileName;
	}
	// this is tricky: we swap the name of the listbox with the name of the file upload input box
	// this is so the posted form field has the correct name
	if (listBoxDomObj.name.indexOf('svyPicInactive_') != -1) //only swap if not already swapped
	{
		$(fileObj).hide()
		// swap names (of "svyPicInactive_" to the active normal field name)
		var holdname = fileObj.name
		fileObj.name = listBoxDomObj.name;
		listBoxDomObj.name = holdname
	}
}

// when user enters a filter search (onkeyup)
function filterServerImageList(filterbox, fieldName) {
	var selbox = document.getElementById('select_' + fieldName);

	var obj = $(selbox)
	var res = obj.data["storedOptions"]
	var opt = ""
	for (var sc = 0; sc < res.length - 1; sc++) {
		var imageFilename = res[sc]
		if (imageFilename.toLowerCase().indexOf(filterbox.value.toLowerCase()) != -1) {
			opt += "<option>" + imageFilename + "</option>"
		}
	}
	obj.html(opt)
}

// load the image into a temp var to check its size, then display it
function pictureSelectorLoadPreview(img, src) {
	var imgPreloader = new Image();
	imgPreloader.onload = function () {

		imgPreloader.onload = null;

		var x = 190;
		var y = 220;
		var imageWidth = imgPreloader.width;
		var imageHeight = imgPreloader.height;
		if (imageWidth > 220 | imageHeight > 180) {
			var wscale = x / imageWidth;
			var hscale = y / imageHeight;
			var scale = (hscale < wscale ? hscale : wscale);
			imageWidth *= scale;
			imageHeight *= scale;
		}

		img.src = src;
		img.width = imageWidth;
		img.height = imageHeight;
	};

	if (!src) {
		src = img.src;
	}
	imgPreloader.src = src;
}

function browseSelectPicture(fieldName) {
	$('#scale_' + fieldName).show(500);
}

// ------------------------------------------
// End Picture Upload/Selector Controls
// ------------------------------------------

// ------------------------------------------
// Month Year Controls
// ------------------------------------------


function handleDateSelector(fieldID) 
{
	var newVal = '';


	if ($('#' + fieldID + "_day").length > 0) {
		if ($('#' + fieldID + "_day") && $('#' + fieldID + "_day").val() != '' && $('#' + fieldID + "_month").val() != '' && $('#' + fieldID + "_year").val() != '') //handle dd/mon/yyyy
		{
			// MN - changed separator from '/' to ' ' as this was not a valid javascript date (except in Chrome where anything goes)
			newVal = '' + $('#' + fieldID + "_day").val() + ' ' + $('#' + fieldID + "_month").val() + ' ' + $('#' + fieldID + "_year").val()
		}
	} else {
		if ($('#' + fieldID + "_month").val() != '' && $('#' + fieldID + "_year").val() != '')		//handle mon-yyyy
		{
			newVal = '1 ' + $('#' + fieldID + "_month").val() + ' ' + $('#' + fieldID + "_year").val()
		}
	}

	if ($('#' + fieldID + "_day").length > 0) {
		//note: changed to CheckDateField from CheckDateInput to support dropdowns as well as text input
		if (!CheckDateField($('#' + fieldID)[0], true)) {//true = show alert
			if ($('#' + fieldID + "_day") != null) {
				//$('#' + fieldID + "_day").val('1')			//reset to 1 - always valid, but 31 feb is not for example
				$('#' + fieldID + "_day")[0].selectedIndex = 0; //reset to no selection
				$('#' + fieldID + "_day").focus()
			} else {
				$('#' + fieldID + "_month").focus()
			}
			newVal = ""    // 
		} 
	} else { 
		//alert('handleDateSelector:failed to locate day dropbox ['+fieldID+']')
		// this is ok, if there is no day dropbox - month/year only
	}
	//date ok, put it in the hidden
	$('#' + fieldID).val(newVal);
}


function handleDaySelector(fieldID) {
	handleDateSelector(fieldID)
}

function handleMonthSelector(fieldID) {
	handleDateSelector(fieldID)
}
function handleYearSelector(fieldID) 
{
	handleDateSelector(fieldID) 
}

// ------------------------------------------
// Month Year Controls
// ------------------------------------------

// ------------------------------------------
// TextArea Controls
// ------------------------------------------

function textboxMultilineMaxNumber(txt,maxLen)
{
	try
	{
		$('#maxlen_'+txt.id).show()
		$('#maxlen_'+txt.id).attr('title','number of characters left to type')
		var numLeft=maxLen-txt.value.length;
		if (numLeft < 0) numLeft = 0;
		var newTxt = '(' + (numLeft) + '&nbsp;/&nbsp;' + maxLen + ')'
		newTxt = newTxt.replace(new RegExp("0", "gm"), "O")

		$('#maxlen_' + txt.id).html(newTxt)
		if(txt.value.length >= (maxLen)) {
			var cont = txt.value;
			txt.value = cont.substring(0,maxLen-1);
			return false;
		};
		$('#'+txt.id).blur(function(){$('#maxlen_'+txt.id).hide()})
	}catch(e){
	}
}

// ------------------------------------------
// TextArea Controls
// ------------------------------------------

// ------------------------------------------
// Yes No Controls
// ------------------------------------------

function YesNoShow(yesNoRadio, selector) {
	// call this onclick (not onchange!)
	if (yesNoRadio.value.toLowerCase() == 'true') {
		$(selector).show()
	} else { 
		$(selector).hide()
	}
}

// ------------------------------------------
//
// ------------------------------------------

