if ((typeof Range !== "undefined") && !Range.prototype.createContextualFragment)
{
    Range.prototype.createContextualFragment = function(html)
    {
        var frag = document.createDocumentFragment(), 
        div = document.createElement("div");
        frag.appendChild(div);
        div.outerHTML = html;
        return frag;
    };
}

function seomv() {
	var newx = seofindx(document.getElementById('seoanchor'));
	var newy = seofindy(document.getElementById('seoanchor'));
	document.getElementById('seodiv').style.left = newx + 'px';
	document.getElementById('seodiv').style.top = newy + 'px';
}

function do_popup(id) {
	popup = new Ext.Window({
		width: 300,
		bodyStyle: "padding: 5px;",
		renderTo: document.body
	});
	
	var template = new Ext.XTemplate(
		'<div id="{id}">'
		+ '	<tpl>{definition}</tpl>'
		+ '</div>'
	);
	template.overwrite(popup.body, definitions[id]);
	
	popup.setTitle(definitions[id].name);
	popup.show();
}

function submitForm(formName, opt, useCaptcha) {
	var opt = opt || {};
	opt.useCaptcha = opt.useCaptcha || false;
	opt.anchor = opt.anchor || 'right';
	
	var form = document.getElementById(formName);
	
	if (checkForm(form, opt) == false) {
		return;
	}
	
	if (useCaptcha == true) {
		checkCaptcha(form);
	} else {
		form.submit();
	}
	
	
}

function checkForm(form, opt) {
	// Define CSS classes
	var errorClass = 'error-field';
	var errorMsgClass = 'error-field-message';
	
	// Define Error Messages
	var requiredFieldMsg = 'This field is required';
	var invalidEmailAddressMsg = 'This field should be an email address in the<br /> format "user@domain.com"';
	
	// Boolean error
	var error = false;
	
	// Remove any existing error classes and error messages
	var errorFields = Ext.DomQuery.select('.' + errorClass, form);
	for (var i = 0; i < errorFields.length; i++) {
		var field = Ext.fly(errorFields[i]);
		field.removeClass(errorClass);
		field.removeAllListeners();
	}
	// Process required fields
	var requiredFields = Ext.DomQuery.select('input.required, select.required, textarea.required', form);
	for (var i = 0; i < requiredFields.length; i++) {
		var field = Ext.fly(requiredFields[i]);
		if (!field.hasClass(errorClass)) {
			if (field.getValue() == '') {
				// Add the error class
				field.addClass(errorClass);
				field.addListener('focus', addErrorMsg, this, {errorMsg: requiredFieldMsg});
				field.addListener('blur', removeErrorMsg);
				
				// Focus on the first field with an error
				if (error === false) {
					field.focus();
					error = true;
				}
			}
		}
	}
	
	// Process email fields
	var emailFields = Ext.DomQuery.select('input.email-address, select.email-address, textarea.email-address', form);
	for (var i = 0; i < emailFields.length; i++) {
		var field = Ext.fly(emailFields[i]);
		if (!field.hasClass(errorClass)) {
			if (!validEmailAddress(field.getValue())) {
				// Add the error class
				field.addClass(errorClass);
				field.addListener('focus', addErrorMsg, this, {errorMsg: invalidEmailAddressMsg});
				field.addListener('blur', removeErrorMsg);
				
				// Focus on the first field with an error
				if (error === false) {
					field.focus();
					error = true;
				}
			}
		}
	}
	
	// If there were any errors, return false
	if (error == true) {
		return false;
	} else {
		return true;
	}
	
	// Function to add an error message to a form field
	function addErrorMsg(e, t, o) {
		// Create an error message
		var field = Ext.get(t);
		var el = Ext.get(Ext.DomHelper.insertAfter(field, {id: field.dom.id + '-msg', tag: 'div', cls: errorMsgClass, html: o.errorMsg}));
		switch (opt.anchor) {
			case 'bottom':
				el.setLocation(field.getLeft(), field.getBottom() + 4);
			break;
			case 'left':
				el.setLocation(field.getLeft() - el.getWidth() - 10, field.getTop());
			break;
			case 'right':
				el.setLocation(field.getRight() + 10, field.getTop());
			break;
			case 'top':
				el.setLocation(field.getLeft(), field.getTop() - el.getHeight() - 4);
			break;
		}
	}
	
	// Function to remove an error message from a form field
	function removeErrorMsg(e, t, o) {
		Ext.fly(t.id + '-msg').remove();
	}
	
	// Function to check if email is valid
	function validEmailAddress(str) {
		if (str.match(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/)) {
			return true;
		} else {
			return false;
		}
	}
}

function checkCaptcha(form) {
	var connection = new Ext.data.Connection().request({
		url: '/assets/scripts/captcha/ajax_response.php',
		method: 'POST',
		params: {
			'recaptcha_response_field': Ext.get('recaptcha_response_field').getValue(),
			'recaptcha_challenge_field': Ext.get('recaptcha_challenge_field').getValue()
		},
		success: function(o) {
			if (o.responseText == '{"success":true}') {
				form.submit();
			} else {
				alert('Verification code incorrect, please try again.');
				Recaptcha.reload();
			}
		}
	});
}

function reloadCaptcha(){
	Recaptcha.reload();	
}

function clearSearch() {
	document.search_box.search_for.value= "";
}
function searchIn(){
	if(document.getElementById("search_for_cms").value == "Search"){
		document.getElementById("search_for_cms").value = "";	
	}
}
function searchOut(){
	if(document.getElementById("search_for_publications").value == ""){
		document.getElementById("search_for_publications").value = "Search Publications";	
	}
}

function mimic(primary, secondary){
	document.getElementById(secondary).value = document.getElementById(primary).value;	
}

var selected_resources = new Array();
function invalidateResource(id){
	if(selected_resources.indexOf(id) != -1){
		selected_resources.splice(selected_resources.indexOf(id), 1);
	} else {
		selected_resources.push(id);
	}
	document.getElementById('selected_resources').value = selected_resources.toString();
}


function updateCalendarDisplay(loc){
	window.location = loc;
}

function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		limitCount.value = limitNum - limitField.value.length;
	}
}
function limitAndMimic(limitField, mimicField, limitCount, limitNum) {
	if (document.getElementById(limitField).value.length > limitNum) {
		document.getElementById(limitField).value = document.getElementById(limitField).value.substring(0, limitNum);
	} else {
		document.getElementById(limitCount).value = limitNum - document.getElementById(limitField).value.length;
	}
	document.getElementById(mimicField).value = document.getElementById(limitField).value;	
}
