﻿
// =============================
//    Clear Input Pre-set Text
// =============================
function initText() {
    $('input.text').each(function() {
        var initValue = this.value;
        this.onfocus = function() { this.value = ''; }
        this.onblur = function()
		{ 
			if(this.value == "")
			{			
				this.value = initValue; 
			}
		}
		
		
    });
}

// =============================
//    Glossary + Tooltips
// =============================



var nuflorGlossaryC = nuflorGlossary.length;
function initGlossary() {
	if ($('#page-glossary').length) {
		return; // not needed on glossary page itself
	}

	$('em.glossary-em').each(function() {
	    $(this).before($(this).text()).remove();
	}); 

	window.setTimeout('_initGlossary(0);', 1);
}

function _initGlossary(i) {

	var title = nuflorGlossary[i]['title'];
	title = title.replace('<em>', '').replace('</em>', '');
	
	// var match = new RegExp('( |\n|\>)' + title + '( |\n|\<|\.|\,)', 'ig');
	var match = new RegExp('^(.*[^a-zA-Z0-9])?(' + title + ')([^a-zA-Z0-9].*)?$', 'igm');

	$('#main').nodesContainingText(title).each(function() {
	    var wrap = true;

	    // don't rewrite certain elements
	    if ($(this).is('a, div.glossary-term .term')) {
	        wrap = false;
	    }
	    if ($(this).parents('div.importance-callout').length > 0 && $(this).attr('class') == 'twoline') {
	        wrap = false;
	    }

	    if (wrap) {
	        var replacement = nuflorGlossary[i]['title'];

	        if (match.test($(this).html())) {
	            var found = $(this).html().replace(match, '$2');

	            // found = found.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); // trim

	            found = $('<div>' + found + '</div>').text();
	            found = found.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); // trim
	            /*
	            if (replacement == '<em>Mycoplasma bovis</em>') {
	                console.log(found);
	                console.log($('<div>' + found + '</div>').text());
	                console.log(replacement);
	            }*/

	            // if first letter is lowercase - then lowercase whole term
	            if (found.substr(0, 4) == '<em>') {
	                if (found.substr(4, 1) == found.substr(4, 1).toLowerCase()) {
	                    replacement = replacement.toLowerCase();
	                }
	            } else {
	                if (found.substr(0, 1) == found.substr(0, 1).toLowerCase()) {
	                    replacement = replacement.toLowerCase();
	                }
	            }

	            $(this).html($(this).html().replace(match, '$1<span class="glossary-term" rel="' + i + '">' + replacement + '</span>$3'));
	            return false;
	        }
	    }
	});

    if (i < nuflorGlossaryC-1) {
    	i++;
    	_initGlossary(i);
    } else {
    	$('span.glossary-term').tooltip({
	        track: false,
	        showURL: false,
	        bodyHandler: function() {
	            var tooltipText = nuflorGlossary[$(this).attr('rel')]['description'];
	            return '<div class="tooltip"><div class="bottom">' + tooltipText + '</div></div>';
	        },
	        top: 1,
	        left: 1
	    });
    }
}
// =============================
//    Size page to push footer
// =============================
function initSizePage() {
    var sizePage = function() {
        var ht = $(window).height();
        var bodyht = (ht - 113);
        $('#bg-wrap-lining').css('min-height', ht + 'px');
        $('#body-wrap').css('min-height', bodyht + 'px');
    };

    $(window).resize(sizePage);
    sizePage();
}
// =============================
//    Print/Email
// =============================
function initPrintEmail() {
    $('#footer-controls .email a').click(function() {
        window.location = "mailto:?body=I thought you would like " + window.location;
        return false;
    });

    $('#footer-controls .print a').click(function() {
        window.print();
        return false;
    });
}
// =============================
//    Resize Text
// =============================
function initTextResize() {
    var setCookie = function(c_name, value, expiredays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + expiredays);
        document.cookie = c_name + "=" + escape(value) +
        ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
    };

    var getCookie = function(c_name) {
        if (document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start, c_end));
            }
        }
        return "";
    };

    $('#footer-controls a.font-sizer').click(function() {
        $('#footer-controls a.font-sizer').removeClass('active');
        $(this).addClass('active');
        $('body').removeClass('fontSmall').removeClass('fontMedium').removeClass('fontLarge');
        if ($(this).hasClass('medium')) {
            $('body').addClass('fontMedium');
            setCookie('fontSize', 'medium');
        } else if ($(this).hasClass('large')) {
            $('body').addClass('fontLarge');
            setCookie('fontSize', 'large');
        } else {
            $('body').addClass('fontSmall');
            setCookie('fontSize', 'small');
        }
    });

    var cookieFSize = getCookie('fontSize');
    if (cookieFSize) {
        $('#footer-controls a.font-sizer.' + cookieFSize).click();
    }
}

// ===================================
//    Ask a Question toggle function
// ===================================
function initAskQuestion() {
    if ($('#page-askquestion').length) {
        $('#page-askquestion .questions .question a').click(function() {
            var wrapper = $(this).parents('.question-wrap:eq(0)');
            if (wrapper.hasClass('active')) {
                //$('.answer', wrapper).slideUp(function() {
                //    wrapper.removeClass('active');
                //});

                $('.answer', wrapper).hide();
                wrapper.removeClass('active');
            } else {
                wrapper.addClass('active');
                //$('.answer', wrapper).slideDown();
                $('.answer', wrapper).show();
            }
        });
    }
}

// =========================================
// Form Validation
// =========================================

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}
function formValidate(form) {
    var errors = '';
    // Loop through required fields
    $('input.required, textarea.required, select.required', form).each(function(i) {
        if ($(this).val() == '') {
            errors += 'error-' + i;
        }
    });
    // Loop through email fields
    $('input.required-email', form).each(function() {
        var isValid = isValidEmailAddress($(this).val());
        if (!isValid) {
            errors = 'bad-email';
        }
    });
    // Report errors, if any
    if (errors.length) {
        if (errors == 'bad-email') {
            window.alert('You must enter a valid email address.');
        }
        else {
            window.alert('Please complete all required fields.');
        }
        return false;
    }
    else {
        return true;
    }
}

// =========================================
// Start it up
// =========================================

$(document).ready(function() {
    /* clear/replace search box text */
    initText();
    
    /* populate glossary and tooltips */
    initGlossary();
    
    /* push footer to bottom */
    initSizePage();
    
    /* print/email button functions */
    initPrintEmail();

    /* text resize button functions */
    initTextResize();
    
    /* askQuestion page functions */
    initAskQuestion();

    /* Apply form validation */
    if ($('input.required', '#content-wrap').length) {
        $('form#contactForm').submit(function() {
            return formValidate(this);
        });
    }

});
