if(!Roving) var Roving = {};

// Clear Email Address Box
function clearDefault(el) {
  if (el.defaultValue==el.value) el.value = ""
}

function doTour(url,popW,popH) {
	var w = 480, h = 340;

	if (document.all || document.layers) {
	   w = screen.availWidth;
	   h = screen.availHeight;
	}

	var leftPos = (w-popW)/2, topPos = (h-popH)/2;

	var TourWindow = window.open(url,'TourWindow','width=' + popW + ',height=' + popH + ',top=' + topPos + ',left=' + leftPos);
	TourWindow.focus();
}

function popHTML(url,width,height,scroll) {
	var mywin = window.open(url,'winHTML','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=' + scroll + ',resizable=1,width=' + width + ',height=' + height + ',left=212,top=84');
    mywin.focus();
}

function showMedia(url) {
    var mywin = window.open(url,'mediaWin','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1');
    mywin.focus();
}

function webExPopup(sessionKey) {
    var url="/learning-center/webinars/live/webinar-redirect.jsp?sessionKey=" + sessionKey;
    mywin = window.open(url,'webexwinHTML');
    mywin.focus();
}

// Resource Center homepage RDD drop-down menu, opens in a new window, unlike the method above. - MM 3-19-2008
function CCRCGoRDDSubmit() {
    var rdd = document.RDDSelection.WhichRDD;
    var listValue = rdd.options[rdd.selectedIndex].value;
    if (listValue != '#') {
        var rddLocation = 'http:\/\/' + document.location.host + '\/index.jsp?pn=' + listValue;
        window.open(rddLocation, 'cclp');
    }
}


// This function converts a String to the application/x-www-form-urlencoded MIME format
function URLEncode(plainText) {
	var validCharSet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	var encodedText = "";
	for (var i = 0; i < plainText.length; i++ ) {
		var ch = plainText.charAt(i);
	    if (ch == ' ') {
		    encodedText += '+';
		} else if (validCharSet.indexOf(ch) != -1) {
		    encodedText += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			var charHexCode = charCode.toString(16);
			encodedText += '%' + charHexCode.toUpperCase();
		}
	}
	return encodedText;
}

// Dropdowns for Hints & Tips homepage
function categoryJump( categoryType ) {
    var vert = document.getElementById( categoryType );
    var listValue = vert.options[vert.selectedIndex].value;
    if (listValue != '#') {
        window.location.href = '\/learning-center\/hints-tips\/' + listValue + '.jsp';
    }
}

// BEGIN: cookies.js
/*
Script Name: Javascript Cookie Script
Author: Alex Bourgoies, with some modifications
Original Script Source URI: http://techpatterns.com/downloads/javascript_cookies.php
Version 1.0.0
Last Update: 3 December, 2007
*/

// this function gets the cookie, if it exists
function Get_Cookie( name ) {

	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ((!start) && (name != document.cookie.substring(0, name.length))){
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

/*only the first 2 parameters are required*/
function Set_Cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	// if the expires variable is set, make the correct expires time, the
	// current script below will set it for x number of days, to make it
	// for hours, delete * 24, for minutes, delete * 60 * 24
	if ( expires ){
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" + value  +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
// END: cookies.js

// All jQuery dependent JS should be placed within this block
// BEGIN: jQuery dependant JS
if(typeof jQuery != 'undefined'){

    // compat for IE & browsers w/o Firebug
    if(typeof console == 'undefined')
        window.console = {log:function(msg){
            if(typeof window._console == 'undefined' && document.location.hash.indexOf('debug') > 0 ){
                window._console = $(document.createElement('div')).attr('style', 'font-family:monospace;padding:5px; margin:5px; width:400px; height:350px; position:absolute; top:0; left:0; background:#fff; border: 2px solid; overflow:auto;')
                        .append($(document.createElement('a')).html('X').css('float', 'right').css('cursor', 'pointer').bind('click', function(){$(this.parent()).hide(500);}));
                $(document.body).append(window._console);
            }
            $(window._console).append($(document.createElement('div')).html(msg).css('margin-bottom', '3px'));
        }};

    // Dynamic client-side form validation
    var ValidationController = function(){
        var messages = {
            'default':{
                required: 'This field is required',
                email: 'This is not a valid email address',
                url: 'This is not a valid URL',
                phone: 'This is not a valid US phone number'
            }
        };
        var controller = {
            errors: {},
            registerMessages: function(msgs){
                for(var x in msgs)
                    messages[x] = msgs[x];
            },
            registerForm: function(form){
                form = $(this.nodeName ? this : form);
                var id = form[0].id;
                if(!id){
                    id = 'el' + parseInt(Math.random(1000)*1000);
                    form.attr('id', id);
                }

                if(typeof ValidationController.errors[id] == 'undefined'){
                    console.log('Registering form ' + id);
                    ValidationController.errors[id] = 0;

                    form.find(":input, select").each(ValidationController.registerFormField);
                    form.find(":input[type='submit']").each(function(){
                        this.disabled = false;
                    });

                    form.submit(function(event){
                        var valid =  ValidationController.validateForm(this);
                        var mainformerr = $('#mainformerror');

                        if(!valid){
                            event.preventDefault();

                            if(mainformerr.length > 0){
                                mainformerr.show();
                                $('html,body').animate({scrollTop: mainformerr.offset().top}, 500);
                            }
                        } else {
                            if(mainformerr.length > 0){
                                mainformerr.hide();
                            }
                            // Disable all submit buttons in this form.
                            $('input[type=submit]', this).attr('disabled', 'disabled');
                            // Go ahead and submit the form.
                            return true;
                        }
                        return false;
                    });

                    if(form.hasClass('markedlabels'))
                        form.prepend($(document.createElement('p')).css('text-align', 'right').addClass('required').html(' Denotes a required field.').prepend(ValidationController.getRequiredMark()));
                }
            },
            getRequiredMark: function(){
                return $(document.createElement('span')).addClass('asterisk required').html('* ');
            },
            unregisterFormField: function(field){
                field = $(this.nodeName ? this : field);
                for(var x in ValidationController.validators)
                    if(field.hasClass(x))
                        field.unbind('blur change', ValidationController.validateFormField);
            },
            registerFormField: function(field){
                field = $(this.nodeName ? this : field);
                for(var x in ValidationController.validators)
                    if(field.hasClass(x)){
                        console.log('Registering form field ' + field.attr('name'));
                        field.bind('blur change', ValidationController.validateFormField);
                        break;
                    }

                if($(field.get(0).form).hasClass('markedlabels'))
                    ValidationController.registerFormFieldLabel(field);
            },
            registerFormFieldLabel: function(field){
                field = $(this.nodeName ? this : field);
                var id = field[0].id;
                if(field.hasClass('required')){
                    console.log('Adding required marker to label for field' + id);
                    $("label[for='"+id+"']").prepend(ValidationController.getRequiredMark());
                }
            },
            validateForm: function(form){
                form = $(this.nodeName ? this : form);
                var id = form[0].id;
                console.log('Validating form ' + id);

                form.find(":input, select").each(ValidationController.validateFormField);
                if(ValidationController.errors[id] < 1){
                    console.log("No errors found. Allowing submission.");
                    return true;
                }
                console.log(ValidationController.errors[id] + " errors found. Stopping submission.");
                return false;
            },
            validateFormField: function(field){
               field = this.nodeName ? this : field;
                var errors = ValidationController.getErrorEl(field);
                $('span', errors).html();

                var validators = ValidationController.validators;
                var classes = field.className.split(' ');
                for (var i = 0, len = classes.length; i < len; i++) {
                    if(validators[classes[i]]){
                        if(!validators[classes[i]](field)){
                            ValidationController.showMessage(field, classes[i]);
                            break;
                        } else {
                            ValidationController.hideMessage(field, classes[i]);
                        }
                    }
                }
            },
            validators: {
                required: function(field){
                    var valid = false;
                    if(field.type == 'checkbox' && field.checked)
                        valid = true;
                    else if (field.nodeName == 'select' && field.selectedIndex > 0)
                        valid = true;
                    else if (field.type != 'checkbox' && field.type != 'select' && jQuery.trim(String($(field).val())).length > 0)
                        valid = true;
                    return valid;
                },
                email: function(field){
                    return field.value.length > 0 ? /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test(field.value) : true;
                },
                url: function(field){
                    return field.value.length > 0 ? /[.]{1}/.test(field.value) : true;
                },
                phone: function(field){
                    return field.value.length > 0 ? /^\(?(\d{3})\)?[-. ]?(\d{3})[-. ]?(\d{4})$/.test(field.value) : true;
                },
                matchPrevious: function(field){
                    var allFields = $(':input');
                    var matches = false;

                    $.each(allFields, function(i){
                        if(this == field){
                            matches = $(this).val() == $(allFields[i-1]).val();
							return false;
                        }
                    });
                    return matches;
                }
            },
            showMessage: function(field, msgType){
                var msg = this.getMessage(field, msgType);
                var errors = this.getErrorEl(field);

                if(!msg){
                    console.log("Couldn't find error msg " + msgType + " for " + field.name);

                } else {
                    console.log('Trying to showing error `' + msg + '` in ' + (errors.length > 0 ?errors[0].id : ' unknown location (coulnd\'t find ' + field.name + '-error)'));
                    if(msg && errors.html() != undefined && errors.html().indexOf(msg) < 0){
                        console.log('Showing error `' + msg + '` in ' + errors[0]);
                        errors.append(msg);
                        ValidationController.errors[field.form.id]++;
                    }
                }
                return false;
            },
            hideMessage: function(field, msgType){
                var msg = this.getMessage(field, msgType);
                var errors = this.getErrorEl(field);

                if(!msg){
                    console.log("Couldn't find error msg " + msgType + " for " + field.name);

                } else {
                    console.log('Trying to remove error `' + msg + '` in ' + (errors.length > 0 ?errors[0].id : ' unknown location (coulnd\'t find ' + field.name + '-error)'));
                    if(msg && errors && errors.html() != undefined && errors.html().indexOf(msg) > -1){
                        console.log('Removing error msg `' + msg + '` from ' + errors[0]);
                        errors.html(errors.html().replace(msg, ''));
                        ValidationController.errors[field.form.id]--;
                    }
                }
            },
            getMessage: function(field, msgType){
                var msg = messages['default'][msgType];

                if(messages[field.name] && typeof messages[field.name][msgType] != 'undefined'){
                    msg = messages[field.name][msgType];
                }
                return msg;
            },
            getErrorEl: function(field){
                var errors = $('#' + field.name + '-error');
                if(errors.length < 1){
                    errors = $(field).nextAll('.errortext');
                }
                return errors;
            }
        };

        $(document).ready(function(){
            $("form.autovalidate").each(controller.registerForm);
        });

        return controller;
    }();


    // Used to center elements within the viewport. Takes into account scroll position on page.
   (function($) {
        $.fn.center = function(options) {
            var pos = {
                top : function() {
                    return $(window).scrollTop();
                },
                height : function() {
                    return window.innerHeight ? window.innerHeight : $(window).height();
                },
                width : function() {
                    return $(window).width();
                }
            };
            return this.each(function() {
                var $this = $(this);
                $this.appendTo("body");
                $this.css({
                    top: pos.top() + parseInt((pos.height() / 2) - ($this.height() / 2)),
                    left: parseInt((pos.width() / 2) - ($this.width() / 2))
                });
            });
        };
    })(jQuery);

    // Image Viewer
    var ImageViewer = function(){
        var index = {};
        var thumbCount =0;
        var $lightbox, $overlay;

        function getGroup(str){ return jQuery.trim(str.replace('thumbnail', '')).toLowerCase(); }
        function capitalise(str){ return str.substring(0,1).toUpperCase() + str.substring(1); }

        // event callbacks
        function close(event){
            event.preventDefault();
            ImageViewer.hide();
        }

        function next(event){
            event.preventDefault();
            var next = $lightbox._current.n + 1;

            if(!index[$lightbox._current.group][next])
                next = 0;

            ImageViewer.display(index[$lightbox._current.group][next]);
        }

        function prev(event){
            event.preventDefault();
            var prev = $lightbox._current.n - 1;
            if(!index[$lightbox._current.group][prev])
                prev = index[$lightbox._current.group].length -1;

            ImageViewer.display(index[$lightbox._current.group][prev]);
        }

        // the singleton viewer object
        var viewer = {
            show: function(){
                if(thumbCount < 2){
                    $("#lightbox a.next, #lightbox a.previous, #lightbox div.count").css('display', 'none');
                }

                if($overlay.css('display') == 'none'){
                    $overlay.css({
                        opacity: 0,
                        display: 'block'
                    });
                    $overlay.fadeTo("fast", 0.75);

                    $(window).scroll(function (){
                        $overlay.center();
                    });
                }

                $lightbox.center();
                $lightbox.css({top: $(window).scrollTop() + 40});
                $lightbox.fadeIn();
				$('select').css('visibility', 'hidden');
            },
            hide: function(){
                $lightbox.fadeOut('fast');
                $overlay.fadeOut('fast');
				$('select').css('visibility', 'visible');
            },
            buildLightbox: function(){
                $('<div id="lightbox" style="display:none;">' +
                    '<div class="wrapper">' +
                        '<a class="close">Close</a>' +
                        '<div class="titlebar">' +
                            '<a class="next">Next</a>' +
                            '<a class="previous">Previous</a>' +
                            '<div class="title"></div><div class="count"></div>' +
                        '</div>' +
                        '<div class="frame"><img class="large" /></div>' +
                    '</div>' +
                '</div><div id="lightbox-overlay" style="display:none;"></div>').appendTo('body');

                $lightbox = $('#lightbox');
                $lightbox.find('.close').click(close);
                $lightbox.find('.next').click(next);
                $lightbox.find('.previous').click(prev);

                $overlay = $('#lightbox-overlay');
                $overlay.click(close);
            },
            indexLightboxLinks: function(){
                var $links = $('a[rel*=thumbnail]');
                $links.each(function(){
                    ImageViewer.indexLink(this);
                });
            },
            indexLink: function(link){
                var title = link.title;
                var group = getGroup(link.rel);
                var $link = $(link);

                if(link.id.length < 1)
                    link.id = 'id-' + Math.floor(Math.random() * 9999);

                var $img = $link.find('img');
                if($img.length > 0)
                    link.title = $img[0].alt;

                if(link.href.indexOf('display_image.jsp') > -1){
                    var ndl = 'display_image.jsp?image_url=';
                    var url = link.href.substring(link.href.indexOf(ndl) + ndl.length);
                    var protocol = window.location.protocol;
                    link.href = protocol + '//' + (protocol.indexOf('https') > -1 ? 'imgssl' : 'img') + '.constantcontact.com/lp/images/standard/bv2/' + url;
                }

                if(!index[group])
                    index[group] = [];

                var exists = false;
                $.each(index[group], function(){
                    if(this.id == link.id){
                        exists = true;
                    }
                });

                if(!exists){
                    thumbCount++;

                    index[group][index[group].length] = {
                        'id': link.id,
                        'group': group,
                        'title': link.title,
                        'ref': link.href,
                        'n': index[group].length
                    }

                    $link.click(function(event){
                        event.preventDefault();

                        while(event.target.nodeName.toLowerCase() != 'a')
                            event.target = event.target.parentNode;

                        ImageViewer.displayIndexed(event.target.id);
                    });
                }
            },
            getFromIndexById: function(id){
                var group = getGroup($('#' + id).attr('rel'));
                var itm;

                for(var i=0, len=index[group].length; i<len; i++)
                    if(index[group][i].id == id)
                        itm = index[group][i];

                return itm;
            },
            displayIndexed: function(id){
                this.display(this.getFromIndexById(id));
            },
            display: function(cfg){
                if(!$lightbox)
                    this.buildLightbox();

                $overlay.height($(document).height()).width($(document).width());

                // populate lightbox display
                $lightbox.find('img.large').attr('src', cfg.ref);
                $lightbox.find('.title').html(cfg.title);
                $lightbox.find('.count').html(capitalise(cfg.group) + ' ' + (cfg.n + 1) + ' of ' + index[cfg.group].length);

                $lightbox._current = cfg;

                $lightbox._preloader = new Image();
                $lightbox._preloader.onload = function(){
                    var $frame = $lightbox.find('.frame');

                    var height = $(window).height() - 200;
                    $frame.height(height > $lightbox._preloader.height ? $lightbox._preloader.height : height);
//                    $frame.width($lightbox._preloader.width);
//                    $lightbox.width($lightbox._preloader.width);
                    $frame.width(720);
                    $lightbox.width(720);

                    ImageViewer.show();
                };
                $lightbox._preloader.src = cfg.ref;
            }
        }

        $(document).ready(viewer.indexLightboxLinks);

        return viewer;
    }();

    // This will find any elements with a class of .swfObject, and replace them with the proper <object/> elements for the current browser.
	// If flash is not installed, the contents of the .swfObject element will be used as alternate content.
     var displaySWF = function(){
		$(".swfObject").each(function(){
			var $this = $(this);
			var alt = $this.html();

			var attrs = {};
			$(this.id + " input.swfProp").each(function(){
				attrs[this.name] = $(this).remove().val();
			});

			var objectAttributes = "";
			var objectParams = "";
			$.each(attrs, function(i){
				objectAttributes += ' ' +i+ '="' +this+ '" ';
				objectParams += '\t<param name="' +i+ '" value="' +this+ '"></param>\n';
			});

			$this.html([
				'<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ' + objectAttributes + '>\n',
				objectParams, alt,
				'</object>\n'
			].join(''));

			if(!document.all){
				var $object2 = $('<object/>');
				$object2.attr(attrs);
                $object2.attr('data', attrs.movie);

				$this.before($object2);
				$object2.html($this);
			}
            $this.css('display', 'block');
		});
     }

    var DropdownController = function() {
        function go() {
            var $sel = $(this).prev('select');
            if ($sel.val() != 'default') {
                document.location.href = $sel.val();
            }
        }

        var controller = {
            registeredDropdowns: [],
            register: function(select) {
                $(this.nodeName ? this : select).next('input').click(go);
                DropdownController.registeredDropdowns.push(select);
            }
        };

        $(document).ready(function() {
            $("select.dropdown").each(controller.register);
        });

        return controller;
    }();
}
// END: jQuery dependant JS