﻿// ------------------------------------------------------
// 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 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
// ------------------------------------------



// ------------------------------------------
// 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;
}

// ------------------------------------------
// End Picture Upload/Selector Controls
// ------------------------------------------

