﻿/* Common */
SepNum = function(aNum) {
	if (aNum < 1000)
		return aNum;
	var res = [];
	aNum = aNum.toString().split('');
	for (var i = aNum.length, j = 0; i > 0; --i) {
		res.unshift(aNum[i - 1]);
		if (++j % 3 == 0 && i != 1)
			res.unshift(',');
	}
	return res.join('');
};
addEvent = function(obj, type, listener, flag) {
	if(obj.addEventListener) {
		obj.addEventListener(type, listener, flag || false);
	}
	else if(obj.attachEvent) {
		obj.attachEvent('on' + type, listener);
	}
}

removeEvent = function(obj, type, listener, flag) {
	if (obj.addEventListener){
		obj.removeEventListener(type, listener, flag || false);
	}
	else if (obj.attachEvent){
		obj.detachEvent('on' + type, listener);
	}
}

CancelBubble = function(e){
	if(!e) return;
	if(e.cancelable){
		if(e.preventDefault&&e.cancelable)
			e.preventDefault();
		if(e.stopPropagation)
			e.stopPropagation();
		return false;
	}
	else if(e.keyCode!=17&&e.keyCode!=16){
		e.cancelBubble=true;
		var f;try{e.keyCode=0}catch(f){}
		return e.returnValue=false
	}
}

RunAjaxScript = function(aHtm) {
    aHtm = aHtm.replace(/\<(\/?)SCRIPT/g, "<$1script").split("<script");
    for (var i = 0; i < aHtm.length; ++i) {
        var source = aHtm[i].split("<\/script>"), e;
        if (source.length > 1) {
            var txt;
            if ((txt = source[0].replace(/^[^>]*>\s*(<!--)?/, "")))
                try {
                (new Function(txt))();
            }
            catch (e)
                        { }
            aHtm[i] = source[1];
        };
    };
    return aHtm.join("")
}

getPK = (function()
{
	var pk = "p" + (new Date() * 1).toString(32), pkn = 0;
	return function(aName)
	{
		if (aName)
			return aName;
		if (pkn > 99999)
		{
			pkn = 0;
			pk = "p" + (new Date() * 1).toString(32);
		};
		return pk + (++pkn).toString(32);
	}
}());

addEvent(window, 'load', new Function('if (!window.DocumentLoaded) DocumentLoaded = "completed"'));

ValidateLocal = function(aForm, aValidationParams, aErrorHighlighting) { /* validation.js is required */
	var validateError, obj, used = {}, rel, val, k;
	for (var item in aValidationParams)
	{
		if (!used[aValidationParams[item][0]] && (obj = aForm[aValidationParams[item][0]]))
		{
			val = k = null;
			rel = obj.getAttribute("relatedField");
			if (rel)
				rel = (rel = aForm[rel]) && (rel.options ? rel.options[rel.selectedIndex] : rel).value.Trim();
			switch (aValidationParams[item][1])
			{
				case ValidateTypeReq:
					if (obj.offsetWidth)
					{
						if (obj.type == 'checkbox')
							k = divFieldErrorText(obj, obj.checked ? null : (aValidationParams[item][2] || "Value is required."), null, aErrorHighlighting);
						else if (obj.type == 'file' && !aForm.getAttribute('uploadisnotreq'))
							k = divFieldErrorText(obj, obj.value.Trim() ? null : (aValidationParams[item][2] || "Value is required."), null, aErrorHighlighting);
					}
					break;
				case ValidateTypePastYear:
					if (obj.offsetWidth && !obj.disabled)
					{
						val = obj.value.Trim();
						if (!val || /^\d+$/.test(val))
						{
							var year = (new Date()).getFullYear(),
								passedYear = parseInt(val, 10);
								
							if (obj.getAttribute("isRequired") == "true" && !val && !rel)
								k = divFieldErrorText(obj, "Value is required", null, aErrorHighlighting);
							else if (passedYear < 1000 || passedYear > year)
								k = divFieldErrorText(obj, "Year must be in range 1000 - " + year, true, aErrorHighlighting);
							else
								divFieldErrorText(obj, null, null, aErrorHighlighting);
						}
						else
						{
							var pref = obj.getAttribute("errorprefix");
							if (pref)
								obj.removeAttribute("errorprefix");
							k = divFieldErrorText(obj, "Year is not valid", null, aErrorHighlighting);
							if (pref)
								obj.setAttribute("errorprefix", pref);
						}
					}
					else
					{
						divFieldErrorText(obj, null, null, aErrorHighlighting);
					}
					break;
				case ValidateTypeReqPastYear:
					var year2 = (new Date()).getFullYear(),
						passedYear2 = parseInt(obj.value, 10);
					if (obj.offsetWidth)
						k = divFieldErrorText(obj, obj.value.Trim() ? (isNaN(obj.value) ? "Year is not valid" : ((passedYear2 >= 1000 && passedYear2 <= year2) || !obj.value.Trim() ? null : "Year must be in range 1000 - " + year2)) : "Value is required", null, aErrorHighlighting);
					break;
				case 'ValidateTypeReqNameExt':
					if (obj.offsetWidth && !obj.disabled)
					{
						var c = SearchAllMenu.contentVisible;
						val = obj.value.Trim();
						if (c == 'content13' || c == 'content14' || aForm.name == 'yesFeedbackForm')
							k = divFieldErrorText(obj, val ? (/^[^\d~\!@#\$%\^&\*\(\)_=\+\{\}\[\]\|\\\:;\",<>\/\?]*$/.test(val) ? null : NameErrorMessage) : 'Value is required', null, aErrorHighlighting);
						else
							k = divFieldErrorText(obj, val ? (validName.test(val) ? null : NameErrorMessage) : "Value is required", null, aErrorHighlighting);
					}
					else
						divFieldErrorText(obj, null, null, aErrorHighlighting);
					break;
				case 'ValidateTypeReqFTPersonName':
					if (obj.offsetWidth)
						k = divFieldErrorText(obj, obj.value.Trim() ? (/^[\w\[\]\/\\\s#\.'`,"\?\(\)\$\^\*\=\+\!\|~&:;@%<>-]*$/.test(obj.value) ? null : "Incorrect character.") : "Value is required.", null, aErrorHighlighting);
					break;
				case 'ValidateTypeFTPersonName':
					k = divFieldErrorText(obj, !obj.disabled && obj.value.Trim() ? (/^[\w\[\]\/\\\s#\.'`,"\?\(\)\$\^\*\=\+\!\|~&:;@%<>-]*$/.test(obj.value) ? null : "Incorrect character.") : (rel ? null : 'Value is required.'), null, aErrorHighlighting);
					break;
				case ValidateTypeAge:
					var age = obj.value.Trim();
					k = divFieldErrorText(obj, !age ? null : (/(^\d+$)/.test(age) ? (((parseInt(age, 10) < 151) && (parseInt(age, 10) > 0)) ? null : "Age must be in range 1 - 150") : "Age is not valid"), null, aErrorHighlighting);
					break;
				case 'minCharacters':
					val = obj.value.Trim().length;
					k = divFieldErrorText(obj, val ? (val >= 6 ? null : 'Password must be at least 6 characters long') : null, null, aErrorHighlighting);
					break;
				case 'maxCharacters':
					var maxCharacters = aValidationParams[item][2];
					val = obj.value.Trim().replace(/\r\n|\n\r|\r(?!\n)|\n(?!\r)/ig, '\r\n').length;
					k = divFieldErrorText(obj, val ? (val <= maxCharacters ? null : 'Value must be ' + maxCharacters + ' characters or less.') : null, null, aErrorHighlighting);
					break;
				case 'ValidateTypePhoneReq':
					var errMessage = null;
					val = obj.value.Trim();
					if (val)
					{
						val = val.replace(/[^\d]/g,'');
						if (val.length == 11 && val.charAt(0) == '1')
							val = val.substr(1);
						if (val.length == 10)
							obj.value = '(' + val.substr(0,3) + ') ' + val.substr(3,3) + '-' + val.substr(6);
						else
							errMessage = 'Phone Number is not correct <nobr>(Ex: (555) 555-5555)</nobr>';
					}
					else
						errMessage = 'Phone is required';
					
					k = divFieldErrorText(obj, errMessage, null, aErrorHighlighting);
					break;
			};
			if (k)
				obj.setAttribute('vlerror', true);
			else
				obj.removeAttribute('vlerror');
			used[aValidationParams[item][0]] = k;
			validateError = k || validateError;
		}
	}

	if (window.top && top.LightviewOpened && !aForm.getAttribute('noresize'))
		setTimeout("top.Lightview.resizeWithinViewport(null, " + (validateError ? "'err'" : true) + ")", 10);
	else if (!aForm.getAttribute('noalert'))
		ShowAlertError(validateError);

	return !validateError;
}

AddSrchAnim = function(aObj, aArea)
{
	var chld = aObj.childNodes;
    for (var i = chld.length; i;)
        if (chld[--i].style)
			chld[i].style.display = 'none';
	var newEl = document.createElement('div');
	newEl.style.textAlign = 'center';
	newEl.style.width = '100%';
	if (aArea == 'frontend')
		newEl.innerHTML = '<h1 style="padding-top: 25px; padding-bottom: 25px; font-family: Georgia; color: #aeaeae;">Searching...</h1><p style="padding-bottom: 45px;"><img src="images/loading.gif" alt="Searching.." width="32" height="32" /></p>';
	else
		newEl.innerHTML = '<h1 style="padding-top: 25px; padding-bottom: 25px; font-family: Georgia; color: #aeaeae;">Searching...</h1><p style="padding-bottom: 45px;"><img src="images/loading.gif" alt="Searching.." width="32" height="32" /></p>';
    aObj.appendChild(newEl);
    return newEl;
}

//this function replaces framework 'ShowWaitTimeout()' because for GA we need another waiting text (see #388)
function ShowWaitTimeout(aContainerID, aValidParam, aForm, aUrl, aLocalValidParam, aArea) {
	aForm.setAttribute('noalert', 1);
	
	var noError = (aLocalValidParam == null || (window.ValidateLocal ? ValidateLocal(aForm, aLocalValidParam, 'InError') : true));
	
	if (!(aValidParam == null || validateUniversal(aForm, aValidParam, 'InError')))
		noError = false;

	ShowAlertError(!noError);
	
    if (noError)
	{
    	var mainContent;
    	if (document.getElementById('ProcessingLightbox_ID'))/*In the future, will need to add another parameter to select the id of "Processing Box"*/
    		Lightview.show({href: '#ProcessingLightbox_ID', options: {closeButton:false, autosize:true}});
    	else if (((mainContent = document.getElementById('resultsBlock')) || (mainContent = document.getElementById('member_search'))) && mainContent.getAttribute('searchingAnimation')){
			var a = $('topActions'),
				m = $(mainContent),
				p = parseInt(m.getStyle('padding-top'),10) + parseInt(m.getStyle('padding-bottom'),10),
				h = m.getHeight();
			if (a){
				h += a.offsetHeight;
				a.setStyle({display: 'none'});
			}
			m.setStyle({height: (h >= (a = AddSrchAnim(mainContent, aArea).offsetHeight) ? h - p : a) + 'px'});
			if (mainContent.id == 'resultsBlock')
				window.scrollTo(0,0);
    	}
        else if ((mainContent = document.getElementById(aContainerID))) {
            AddSrchAnim(mainContent, aArea);
        }
        setTimeout("document.getElementById('" + aForm.id + "').submit();", 3000);
        return true;

    }
    return false;
}

function Show(showLink, showTarget) 
{
	showLink.style.display = 'none';
	showTarget.style.display = '';
}

function ToggleDisplayStyle(objectID) 
{
    var obj = document.getElementById(objectID);
    if (obj == null)
        return;

    obj.style.display = (obj.style.display == 'none') ? '' : 'none';
}

/* USED WITH JQUERY ADVANCED SEARCH ANIMTATION */
AdvArrow = function(aObj, aCont)
{
	var advBox = document.getElementById(aCont);
	if(advBox)
	{
		var advNotShow = advBox.style.display == "none",
			advSpan = aObj.getElementsByTagName('SPAN')[0];
			
		if (advSpan)
			advSpan.innerHTML = advNotShow ? 'Less' : 'More';
		aObj.style.backgroundPosition = advNotShow ? '100% 0' : '100% -' + aObj.offsetHeight + 'px';
		aObj.setAttribute('sliding',true);
		for (var inp = advBox.getElementsByTagName("INPUT"), j = inp.length; j > 0; --j)
		{
			if(advNotShow)
				inp[j-1].removeAttribute('style');
			else
				inp[j-1].style.backgroundColor = "#ffffff";
			inp[j-1].disabled = !advNotShow;
		}
	}
	if (window.event)
	{
		event.cancelBubble = true;
		event.returnValue = false;
	};
}

CheckTextNode = function(aId) {
    var obj = document.getElementById(aId);
    return (obj && (obj = obj.firstChild) && obj.nodeName == "#text" && obj.data.Trim()) ? obj : false;
}

SaveRecordPopulateBase = function(prefix, frameDoc) {

    var obj, arr = [], form = frameDoc['AddSavedRecord'];
    //clear values and errors for previous person
    form.reset();
    arr = form.elements
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].type == 'text' || arr[i].type == 'select-one')
            arr[i].value = '';
        if (arr[i].className.indexOf('InError') != -1)
            arr[i].className = arr[i].className.replace(new RegExp("InError"), '')
    }
    arr = form.getElementsByTagName('div')
    for (var i = 0; i < arr.length; i++)
        if (arr[i].className == 'FieldErrorText') { arr[i].parentNode.removeChild(arr[i]); i-- }
    frameDoc.getElementById(prefix + 'Gender').value = 'Unknown';
    // set values for new person
    if ((obj = CheckTextNode('firstNameDetails')))
        frameDoc.getElementById(prefix + 'FirstName').value = obj.data;
    if ((obj = CheckTextNode('middleNameDetails')))
        frameDoc.getElementById(prefix + 'MiddleName').value = obj.data;
    if ((obj = CheckTextNode('lastNameDetails')))
        frameDoc.getElementById(prefix + 'LastName').value = obj.data;

    if ((obj = CheckTextNode('birthMonth')))
        frameDoc.getElementById(prefix + 'BirthMonth').options[parseInt(obj.data, 10)].selected = true;
    if ((obj = CheckTextNode('birthDay')))
        frameDoc.getElementById(prefix + 'BirthDay').options[parseInt(obj.data, 10)].selected = true;
    if ((obj = CheckTextNode('birthYearId')))
        frameDoc.getElementById(prefix + 'BirthYear').value = obj.data;
        
    if ((obj = CheckTextNode('deathMonth')))
        frameDoc.getElementById(prefix + 'DeathMonth').options[parseInt(obj.data, 10)].selected = true;
    if ((obj = CheckTextNode('deathDay')))
        frameDoc.getElementById(prefix + 'DeathDay').options[parseInt(obj.data, 10)].selected = true;
    if ((obj = CheckTextNode('deathYearId')))
        frameDoc.getElementById(prefix + 'DeathYear').value = obj.data;
        
    if ((obj = CheckTextNode('birthLocation')))
        frameDoc.getElementById(prefix + 'BirthLocation').value = obj.data;
    if ((obj = CheckTextNode('deathLocation')))
        frameDoc.getElementById(prefix + 'DeathLocation').value = obj.data;
    if ((obj = CheckTextNode('collection')))
        frameDoc.getElementById(prefix + 'RecordSource').value = obj.data;
}

/*
Shows "processing..." instead of button
*/
function DisplayProcessingElement(divToHide, divToShow) {
    jQuery("#" + divToHide).hide();
    jQuery("#" + divToShow).show();
}

/*
Resets the src of the searching image
*/
function ResetSearching() {
    var img = document.getElementById('searching');
    img.src = img.src;
}

RegisterLightboxHidden = function(){
	document.stopObserving('lightview:opened', RegisterLightboxOpened);
	document.stopObserving('lightview:hidden', RegisterLightboxHidden);
}

SetFocusObj = function(aId, aAltId){
	aId = document.getElementById(aId) || (aAltId && document.getElementById(aAltId));
	if (aId)
	{
		var err;
		try
		{
			aId.focus();
			if (aId.type == 'text')
				aId.select();
		}
		catch(err){}
	}
}

RegisterLightboxOpened = function(){
	SetFocusObj('Registration_R1_RegisterFirstName','submit_trial');
}

PageTrackEvent = function(aCategory, aAction, aLabel) {
	if(!window.pageTracker)
		setTimeout('PageTrackEvent(' + aCategory + ', ' + aAction + ', ' + aLabel + ')', 20);
	else
		pageTracker._trackEvent(aCategory, aAction, aLabel);
}

ShowRegisterLightbox = function(aPageTracker){
	if (window.DocumentLoaded)
	{
		document.observe('lightview:opened', RegisterLightboxOpened);
		document.observe('lightview:hidden', RegisterLightboxHidden);
		Lightview.show({href: '#Register_Lightbox_ID', options: {closeButton:false, autosize:true}});
		if (aPageTracker)
			PageTrackEvent('Register', 'ShowLightbox', 'Show Register Lightbox');
	}
}

/* SelfTree Lightbox */
SelfTreeLightboxHidden = function() {
	$('SelfTreeFrame').style.height = 'auto';
	$('SelfTreeResult').innerHTML = '<div class="center" style="padding-bottom: 140px;"><h2 class="processing">Processing...</h2><p><img src="images/loading_light.gif" alt="Searching.." width="32" height="32" /></p><br /><br /><p>Please wait a moment while we compile the results of your request.</p></div>'
	document.stopObserving('lightview:opened', SelfTreeLightboxOpened);
	document.stopObserving('lightview:hidden', SelfTreeLightboxHidden);
}

SelfTreeLightboxOpened = function() {
	CbOS.Ajax({
        query:  $('SelfTreeFrame').getAttribute('ajaxurl'),
        success: function(aHtml)
        {
            if (aHtml == 'ERR')
				return location.reload();
            if (window.LightviewOpened)
            {
                var lv = document.getElementsByClassName('lv_contentBottom')[0],
					s = $('SelfTreeFrame');
                if (lv.offsetHeight == s.offsetHeight)
                    lv.style.overflow = 'visible';
                $('SelfTreeResult').innerHTML = RunAjaxScript(aHtml);
                SetFocusLightboxOpened();
                if ($('ProblemDetailId'))
                {
                    $('SelfTreeResult').innerHTML = $('ProblemDetailId').innerHTML;
                    var goBackLink = $('GoBackLink');
                    if (goBackLink)
						goBackLink.onclick = function() { Lightview.hide(); return false }
                }
                if (lv.offsetHeight <= s.offsetHeight)
                    Lightview.resizeWithinViewport(null, true)
                else
                    s.style.height = '100%';
                PageTrackEvent('Register', 'ShowLightbox', 'Show Register Lightbox');
            }
        }
    });
}
SelfTreeFrameRun = function(aURL){
	if(window.DocumentLoaded && aURL)
	{
		document.observe('lightview:opened', SelfTreeLightboxOpened);
		document.observe('lightview:hidden', SelfTreeLightboxHidden);
		$('SelfTreeFrame').setAttribute('ajaxurl', aURL);
		Lightview.show({href: '#SelfTreeFrame', options: {closeButton:false, autosize:true}});
	}
}

/* Other */

ShowAdditionalRows = function(aThis, aTableID)
{
	var rows = document.getElementById(aTableID).getElementsByTagName('TR');

	aThis.style.display = 'none';
	for (var i = rows.length; i;)
		rows[--i].style.display = 'block';
}

AdditionValidateAncAlerts = function(aFrm, aCount, aErrorHighlighting)
{
	var relFields = ['_FirstName','_Location','_BirthYear','_DeathYear'],
		pref, obj, isReq, err;

	for (var i = 1; i <= aCount; ++i)
	{
		pref = 'AncestorAlerts_R' + i;
		isReq = false;
		
		obj = aFrm[pref + '_LastName'];
		if (obj && obj.offsetWidth)
		{
			if (!obj.value.Trim())
			{
				for (var j = relFields.length; j;)
					if (aFrm[pref + relFields[--j]].value.Trim())
					{
						isReq = true;
						break;
					}
					err = divFieldErrorText(obj, (isReq ? 'Last Name is required' : null), null, aErrorHighlighting) || err;
			}
			else
				err = divFieldErrorText(obj, (validName.test(obj.value) ? null : NameErrorMessage), null, aErrorHighlighting) || err;
		}
	}
	return !err;
}
// Goes back to the parent window and navigates it to another place.
// If there is no parent window, then it just navigates the current window.
function toggleHide(hideImg, hideTarget, imgSrcHide, imgSrcShow)
{
	var bHidden = (hideTarget.style.display == 'none');
	
	hideTarget.style.display = bHidden ? '' : 'none';
	setTimeout("document.getElementById('" + (hideImg.id || (hideImg.id = getPK())) + "').src = '" + (bHidden ? imgSrcHide : imgSrcShow) + "'",40);
}

OpenNewWindow = function(aUrl, aName, aEvent, aParam) {
	var winName = aName + 'NewWindow',
            nw = window[winName],
            e;

	if (nw && !nw.closed) {
		if (nw.location)
			nw.location.href = aUrl;
		else
			open(aUrl, '_blank', (aParam || ''));
	}
	else
		nw = window[winName] = open(aUrl, aName, (aParam || ''));

	try {
		nw.focus();
	}
	catch (e)
      { }
	if (aEvent)
		return CancelBubble(aEvent)
}

GetOpenerWindow = function(aWin)
{
	var e;
	
	try
	{
		return ((aWin = aWin.opener) && !aWin.closed && aWin);
	}
	catch(e)
	{
		return false;
	}
}

// Goes back to the parent window and navigates it to another place.
// If there is no parent window, then it just navigates the new window.
NavigateToOpener = function(aHref, aName)
{
	var win = GetOpenerWindow(window);

	if (win)
	{
		win.location = aHref;
		win.focus();
	}
	else
		OpenNewWindow(aHref, aName);
}

SetFocusLightboxHidden = function()
{
	document.stopObserving('lightview:opened', SetFocusLightboxOpened);
	document.stopObserving('lightview:hidden', SetFocusLightboxHidden);
}

SetFocusLightboxOpened = function()
{
	SetFocusLightboxHidden();
	
	var frm = document.getElementById('lightview').getElementsByTagName('FORM')[0];
	if (frm && (frm.id || (frm.id = getPK())))
		SetFocusForm(frm.id);
}

SetFocusLightbox = function()
{
	document.observe('lightview:opened', SetFocusLightboxOpened);
	document.observe('lightview:hidden', SetFocusLightboxHidden);
}

var timer;
var current = "testimonial1";
		
function testimFade (current, next) {
	$(current).fade({duration: 0.4});
	$(next).appear({duration: 0.4, delay: 0.4});
}
		
function testimForward(ifWaitFirst) {
	var nextNumber = current.substring(11)*1;
	var next;
	var temp = function () { testimForward(0); };
			
			
	if(ifWaitFirst == 1)
	{
		timer = window.setTimeout(temp, 15000);
	}
	else
	{
		clearTimeout(timer);
				
		nextNumber++;
		next = "testimonial" + nextNumber;
				
		//if there isn't another testimonial, moves 'next' to the first testimonial
		if(!document.getElementById(next)) {
			next = "testimonial1";
		}
				
		//old testimonial fades out, new fades in.  Updates current
		testimFade(current, next);
		current = next;
				
		//calls temp--testimForward(0)--after 15 seconds
		timer = window.setTimeout(temp, 15000);
	}
}
		
function testimBackward() {
	var prevNumber = current.substring(11)*1;
	var prev;
			
	prevNumber--;
	prev = "testimonial" + prevNumber;
			
	//tests if prev exists, if not, moves it to the last testimonial
	if(!document.getElementById(prev)) {
		var i=1;
		while (document.getElementById("testimonial" + i)) 
		{
			prev = "testimonial" + i;
			i++;
		}				
	}
			
	//old testimonial fades out, new fades in.  Updates current
	testimFade(current, prev);
	current = prev;
			
	//clear the timeout, start testimForward with delay
	clearTimeout(timer); 
	testimForward(1);
}
		


	