//dynamicShadow - Creates a dynamic shadow for images
//Defaults to shadow.gif, 10 width, no offset
//Note: Prototype Framework
function dynamicShadow(shadowURL, containerID, shadowWidth, shadowOffset) {
    var shadowURL = (shadowURL == null) ? "../images/global/shadowTest.gif" : shadowURL;
    var containerID = (containerID == null) ? "page-container" : containerID;
    var shadowWidth = (shadowWidth == null) ? 10 : shadowWidth;
    var shadowOffset = (shadowOffset == null) ? 0 : shadowOffset;


    var images = $$(
		'#' + containerID + ' img.shadow,'
		+ '#' + containerID + ' img.shadowLeft,'
		+ '#' + containerID + ' img.shadowRight,'
		+ '#' + containerID + ' img.shadowCenter');
    var imageClone;
    var imageHeight;
    var imageWidth;
    var shadowContainer;
    var shadowDiv = [];

    images.each(function (imageObject) {
        imageClone = Object.extend(imageObject);
        imageHeight = imageObject.getHeight();
        imageWidth = imageObject.getWidth();
        imageClass = imageObject.className;

        // Create the Shadow Container
        shadowContainer = new Element('div');
        shadowContainer.addClassName('shadowContainer');
        shadowContainer.addClassName(imageClass);
        shadowContainer.setStyle({
            position: 'relative',
            padding: shadowWidth + 'px',
            width: imageWidth + 'px',
            height: imageHeight + 'px',
            background: 'transparent'
        });

        // Create Top Left Div
        shadowDiv[0] = new Element('div');
        shadowDiv[0].setStyle({
            position: 'absolute',
            top: 0,
            left: 0,
            width: shadowWidth + 'px',
            height: shadowWidth + 'px',
            background: 'transparent url("' + shadowURL + '") top left no-repeat'
        });
        shadowContainer.insert({ bottom: shadowDiv[0] });

        // Create Top Right Div
        shadowDiv[1] = new Element('div');
        shadowDiv[1].setStyle({
            position: 'absolute',
            top: 0,
            right: 0,
            width: shadowWidth + 'px',
            height: shadowWidth + 'px',
            background: 'transparent url("' + shadowURL + '") top right no-repeat'
        });
        shadowContainer.insert({ bottom: shadowDiv[1] });

        // Create Bottom Right Div
        shadowDiv[2] = new Element('div');
        shadowDiv[2].setStyle({
            position: 'absolute',
            bottom: 0,
            right: 0,
            width: shadowWidth + 'px',
            height: shadowWidth + 'px',
            background: 'transparent url("' + shadowURL + '") bottom right no-repeat'
        });
        shadowContainer.insert({ bottom: shadowDiv[2] });

        // Create Bottom Left Div
        shadowDiv[3] = new Element('div');
        shadowDiv[3].setStyle({
            position: 'absolute',
            bottom: 0,
            left: 0,
            width: shadowWidth + 'px',
            height: shadowWidth + 'px',
            background: 'transparent url("' + shadowURL + '") bottom left no-repeat'
        });
        shadowContainer.insert({ bottom: shadowDiv[3] });

        // Create Center Top Div
        shadowDiv[4] = new Element('div');
        shadowDiv[4].setStyle({
            position: 'absolute',
            top: 0,
            left: shadowWidth + 'px',
            width: imageWidth + 'px',
            height: shadowWidth + 'px',
            background: 'transparent url("' + shadowURL + '") top center no-repeat'
        });
        shadowContainer.insert({ bottom: shadowDiv[4] });

        // Create Center Right Div
        shadowDiv[5] = new Element('div');
        shadowDiv[5].setStyle({
            position: 'absolute',
            top: shadowWidth + 'px',
            right: 0,
            width: shadowWidth + 'px',
            height: imageHeight + 'px',
            background: 'transparent url("' + shadowURL + '") center right no-repeat'
        });
        shadowContainer.insert({ bottom: shadowDiv[5] });

        // Create Center Bottom Div
        shadowDiv[6] = new Element('div');
        shadowDiv[6].setStyle({
            position: 'absolute',
            bottom: 0,
            right: shadowWidth + 'px',
            width: imageWidth + 'px',
            height: shadowWidth + 'px',
            background: 'transparent url("' + shadowURL + '") bottom center no-repeat'
        });
        shadowContainer.insert({ bottom: shadowDiv[6] });

        // Create Center Right Div
        shadowDiv[7] = new Element('div');
        shadowDiv[7].setStyle({
            position: 'absolute',
            top: shadowWidth + 'px',
            left: 0,
            width: shadowWidth + 'px',
            height: imageHeight + 'px',
            background: 'transparent url("' + shadowURL + '") center left no-repeat'
        });
        shadowContainer.insert({ bottom: shadowDiv[7] });

        imageObject.replace(shadowContainer);

        shadowContainer.insert({ bottom: imageClone });

    });

    return false;
}

//First and Last LI Selector
//Note: Prototype Driven
function liFirstLast() {
    var firstLIs = $$('ul > li:first-child');
    var lastLIs = $$('ul > li:last-child');

    firstLIs.each(function (liFirst) {
        liFirst.addClassName('first');
    });

    lastLIs.each(function (liLast) {
        liLast.addClassName('last');
    });
}

//External Link Helper
//Updates Links with External Relation to
//use target="_blank"
function externalLinks() {
    var links = $$('a[rel=external]');

    links.each(function (externalLink) {
        externalLink.writeAttribute('target', '_blank');
    });
}

//Input Clear
//Clears text inputs on a page on focus
//Note: Prototype driven
function inputClear() {
    var textInputs = $$('fieldset#siteSearch input[type="text"]');

    textInputs.each(function (textInput) {
        textInput.initialValue = textInput.value;
        textInput.observe('focus', function (event) {
            if (textInput.value == textInput.initialValue) {
                textInput.clear();
            }
        });
        textInput.observe('blur', function (event) {
            if (textInput.value.blank() == true) {
                textInput.value = textInput.initialValue;
            }
        });
    });
}

//Height Balance
//Normalizes the height of the elements passed in,
//based on the number of columns desired
function heightBalance(balanceElements, columns) {
    balanceElements.eachSlice(columns, function (balanceElementSlice) {
        var sliceHeight = balanceElementSlice.max(function (sliceElement) {
            return sliceElement.getHeight();
        });

        balanceElementSlice.each(function (balanceElement) {
            balanceElement.setStyle({
                height: sliceHeight + 'px'
            });
        });
    });
}

/*function tabbedContent(){
var contentTabs = $$('.category1, .category2');
	
if(!contentTabs[0]){
return false;
}
	
var currentIndex = 0;
	
var contentNavigation = $$('.category1Tab, .category2Tab');;

var navItems = new Array();
var navItemAnchors = new Array();
	
contentTabs.each(function(contentTab, index){
		
var contentTitle = contentTab.down('h2');
navItems[index] = new Element('li');
navItemAnchors[index] = new Element('a');
navItemAnchors[index].update(contentTitle.innerHTML);
		
navItems[index].insert({
top: navItemAnchors[index]			   
});
		
contentNavigation.insert({
bottom: navItems[index]   
});
		
if(index == 0){
navItems[index].addClassName('activeTab');
contentTab.addClassName('active');
}
		
navItemAnchors[index].observe('click', function(event){
contentTabs[currentIndex].removeClassName('active');
navItems[currentIndex].removeClassName('activeTab');
			
currentIndex = index;
contentTabs[currentIndex].addClassName('active');
navItems[currentIndex].addClassName('activeTab');
			
event.stop();
});
		
contentTitle.remove();
});
}*/

//Carousel Controls
//Rotates through UL.carousel and gives control and updates OL.carousel
function carousel() {
    var items = $$('ul.carousel li ul.breakoutCopy'); //Array of carousel list items
	//console.log(items);

    if (!items[0]) return false; //Let's check to be sure this exists

    var controls = $$('ul.carousel li > a');
	//console.log(controls);
    var queue = Effect.Queues.get('carouselQueue'); //create the queue for the animation sequence.

    items.each(function (item, index) {
        if (item.empty()) {
            item.remove();
        }
        if (index != 0) {
            item.setOpacity(0);
            item.setStyle({
                top: '-999em',
                zIndex: '0'
            });
        }

        controls[index].observe('click', function (event) {
            controls[index].fire('bayvillage:carouselUpdate', { indexMove: -(index - currentItem) });
            carousel.stop();
            event.stop();
        });
    });

    var items = $$('ul.carousel li ul.breakoutCopy'); //we've removed empties, now redefine variable correctly.

    var currentItem = 0; //We need to make sure our current items starts with the 1st, ala the 0

    var previousItem = items.size(); //Previous item is the last one, grabbing the total amount tells us what # that is.

    controls[currentItem].addClassName('current'); //Add a current class to the active items specific control

    document.observe('bayvillage:carouselUpdate', function (event) {
        if (queue.effects.size() == 0) {

            controls[currentItem].removeClassName('current'); //Remove the class from the previous items control.
            var itemMove = event.memo.indexMove;

            previousItem = currentItem;
            currentItem = (items.size() + ((currentItem - itemMove) % items.size())) % items.size(); //incrementally step up the index

            if (previousItem == currentItem) { //Stops the user from choosing the already current item twice.
                controls[currentItem].addClassName('current');
                return false;
            }

            new Effect.Parallel([new Effect.Opacity(items[previousItem], {
                from: 1,
                to: 0,
                duration: 1,
                afterFinish: function () {
                    items[previousItem].setStyle({
                        top: '-999em',
                        zIndex: 0
                    });
                }
            }), new Effect.Opacity(items[currentItem], {
                from: 0,
                to: 1,
                duration: 1,
                beforeStart: function () {
                    items[currentItem].setStyle({
                        top: '-358px',
                        zIndex: 1000
                    });
                }
            })], {
                queue: {
                    position: 'end',
                    scope: 'carouselQueue',
                    limit: 2
                }
            });

            controls[currentItem].addClassName('current');

        };

    });

    carousel = new PeriodicalExecuter(function () {
        controls[currentItem].fire('bayvillage:carouselUpdate', { indexMove: -1 });
    }, 8);

}

//Header Helper
//Creates various hover classes for the header controls
function headerHelper() {
    var hoverLists = $$('.quickLinks');
	//console.log(hoverLists);

    hoverLists.each(function (hoverList) {
        hoverList.observe('mouseenter', function (event) {
            hoverList.addClassName('hover');
        });
        hoverList.observe('mouseleave', function (event) {
            hoverList.removeClassName('hover');
        });
    });
}

function tabbedContent() {
    var contentTabs = $$('section.category1', 'section.category2', 'section.category3');
    //window.log(contentTabs);
    if (!contentTabs[0]) {
        return false;
    }

    var currentIndex = 0;

    var footerItem = $('footer');
    var navItems = $$('#footerContent h2');
    var navItemAnchors = $$('#footerContent h2 a');
    //window.log(navItems);
    contentTabs.each(function (contentTab, index) {

        if (index == 0) {
            //window.log(currentIndex);
            //console.log(navItems[index]);
            navItems[index].addClassName('activeTab');
            contentTab.addClassName('active');
            footerItem.addClassName('active' + currentIndex);
            //window.log(currentIndex);
            //window.log(footerItem);
        }

        navItemAnchors[index].observe('click', function (event) {
            contentTabs[currentIndex].removeClassName('active');
            navItems[currentIndex].removeClassName('activeTab');
            footerItem.removeClassName('active' + currentIndex);

            currentIndex = index;
            contentTabs[currentIndex].addClassName('active');
            navItems[currentIndex].addClassName('activeTab');
            footerItem.addClassName('active' + currentIndex);

            event.stop();
        });

    });
}

/*//Columned List Sort Utility
//Properly reorganizes a list to allow for columns
function listSorter(list, columns) {
var numColumns = columns;
var listItems = list.childElements();
window.log(listItems)
var totalItems = listItems.size();
	
var sortedItems = [];
	
var numRows = totalItems / numColumns;
numRows = numRows.ceil();
	
numRows.times(function(n){
var sortedRow = [];
	
numColumns.times(function(m){
var listNumerator = n + (m * numRows);
			
if(listItems[listNumerator]){
sortedRow[m] = listItems[listNumerator];
}
});
		
sortedItems[n] = sortedRow;
});
		
sortedItems = sortedItems.flatten();
		
sortedItems.each(function(sortedItem){
list.insert({
bottom: sortedItem
});
});
	
return sortedItems;
}*/

//Columned List Sort Utility
//Properly reorganizes a list to allow for columns
function listSorter(listArray, columns) {
    var numColumns = columns;
    var lists = listArray;

    lists.each(function (list) {
        var listItems = list.childElements();
        //window.log(listItems)
        var totalItems = listItems.size();

        var sortedItems = [];

        var numRows = totalItems / numColumns;
        numRows = numRows.ceil();

        numRows.times(function (n) {
            var sortedRow = [];

            numColumns.times(function (m) {
                var listNumerator = n + (m * numRows);

                if (listItems[listNumerator]) {
                    sortedRow[m] = listItems[listNumerator];
                }
            });

            sortedItems[n] = sortedRow;
        });

        sortedItems = sortedItems.flatten();

        sortedItems.each(function (sortedItem) {
            list.insert({
                bottom: sortedItem
            });
        });

        return sortedItems;

    });

}

/*function stickyFooter() {
	var footerHeight = $('footer').getHeight();
	console.log(footerHeight);
	$('main').setStyle({
    	paddingBottom: 253 + 'px'
    });
	$('footer').setStyle({
    	marginTop: -253 + 'px'
    });
}
*/

//Copy Address Prefill
//Copies one set of filled out address fields into another

function addressPrefill() {

	if(!$('donor')) return false;
	var donnorFields = $('donor').select('label.prefill input, label.prefill select');
	var billingFields = $('billing').select('label.prefill input, label.prefill select');
	
	var checkboxes = $$('label#addressPrefill input');
	
	//console.log(donnorFields);
	//console.log(billingFields);
	
	checkboxes.each(function(checkbox) {
		checkbox.observe('click', function() {
			if(this.checked) {
				//console.log('checked');
				// The checkbox is checked, copy the information over
				
				donnorFields.each(function(donnorField, index){
					billingFields[index].value = donnorField.value;
				});


			} else {
				//console.log('not checked');
				// The checkbox is unchecked, remove any unchanged fields
				
				donnorFields.each(function(donnorField, index){
					if(billingFields[index].value == donnorField.value){
						billingFields[index].value = "";
					}
				});				
			}
		});
	});
}


//Font increase and decrease functionality
function fontResizer() {
	var increaseButton = $('fontIncrease');
	var decreaseButton = $('fontDecrease');
	var header = $('header');

	if (!header)
		return false;

	var main = $('article');

	var footer = $('footer');

	var currentSize = 'normal';

	var subNavigationItems = $$('#navMain > ul > li > ul > li ');

	var fontCookie = readCookie('aodFonts');



	window.log("fontcookie",fontCookie);



	if (fontCookie == 'smallest') {

		main.addClassName('smallest');

		currentSize = 'smallest';

	} else if (fontCookie == 'small') {

		main.addClassName('small');

		currentSize = 'small';

	} else if (fontCookie == 'normal') {

		main.addClassName('normal');

		currentSize = 'normal';

	} else if (fontCookie == 'large') {

		main.addClassName('large');

		currentSize = 'large';

	} else if (fontCookie == 'largest') {

		main.addClassName('largest');

		currentSize = 'largest';

	}



	increaseButton.on('click', function (event) {

		window.log('clicked increase button');



		if (currentSize == 'normal') {

			main.removeClassName('normal');

			main.addClassName('large');

			currentSize = 'large';

			setCookie('aodFonts', 'large', 90, '/', '', '');

			window.log(currentSize);

			event.stop();

			return false;

		} else if (currentSize == 'small') {

			main.removeClassName('small');

			main.addClassName('normal');

			currentSize = 'normal';

			setCookie('aodFonts', 'normal', 90, '/', '', '');

			window.log(currentSize);

			//	heightBalance(subNavigationItems, 4);

			event.stop();

			return false;

		} else if (currentSize == 'smallest') {

			main.removeClassName('smallest');

			main.addClassName('small');

			currentSize = 'small';

			setCookie('aodFonts', 'small', 90, '/', '', '');

			window.log(currentSize);

			//	heightBalance(subNavigationItems, 4);

			event.stop();

			return false;

		} else if (currentSize == 'large') {

			main.removeClassName('large');

			main.addClassName('largest');

			currentSize = 'largest';

			setCookie('aodFonts', 'largest', 90, '/', '', '');

			window.log(currentSize);

			//	heightBalance(subNavigationItems, 4);

			event.stop();

			return false;

		} else if (currentSize == 'largest') {

			setCookie('aodFonts', 'largest', 90, '/', '', '');

			//	heightBalance(subNavigationItems, 4);

			event.stop();

			return false;

		}

	});



	decreaseButton.on('click', function (event) {

		window.log('clicked decrease button');



		if (currentSize == 'normal') {

			main.removeClassName('normal');

			main.addClassName('small');

			currentSize = 'small';

			setCookie('aodFonts', 'small', 90, '/', '', '');

			window.log(currentSize);

			//	heightBalance(subNavigationItems, 4);

			event.stop();

			return false;

		} else if (currentSize == 'small') {

			main.removeClassName('small');

			main.addClassName('smallest');

			currentSize = 'smallest';

			setCookie('aodFonts', 'smallest', 90, '/', '', '');

			window.log(currentSize);

			//	heightBalance(subNavigationItems, 4);

			event.stop();

			return false;

		} else if (currentSize == 'smallest') {

			setCookie('aodFonts', 'smallest', 90, '/', '', '');

			//	heightBalance(subNavigationItems, 4);

			event.stop();

			return false;

		} else if (currentSize == 'large') {

			main.removeClassName('large');

			main.addClassName('normal');

			currentSize = 'normal';

			setCookie('aodFonts', 'normal', 90, '/', '', '');

			window.log(currentSize);

			//	heightBalance(subNavigationItems, 4);

			event.stop();

			return false;

		} else if (currentSize == 'largest') {

			main.removeClassName('largest');

			main.addClassName('large');

			currentSize = 'large';

			setCookie('aodFonts', 'large', 90, '/', '', '');

			window.log(currentSize);

			//	heightBalance(subNavigationItems, 4);

			event.stop();

			return false;

		}

		/**/

		//heightBalance(subNavigationItems, 4);

	});

}



// Cookie Functions
// Set the cookie 
function setCookie(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 + "=" + escape(value) +
	((expires) ? ";expires=" + expires_date.toGMTString() : "") +
	((path) ? ";path=" + path : "") +
	((domain) ? ";domain=" + domain : "") +
	((secure) ? ";secure" : "");
}

// Read the cookie 
function readCookie(name) {
    var needle = name + "=";
    var cookieArray = document.cookie.split(';');
    for (var i = 0; i < cookieArray.length; i++) {
        var pair = cookieArray[i];
        while (pair.charAt(0) == ' ') {
            pair = pair.substring(1, pair.length);
        }
        if (pair.indexOf(needle) == 0) {
            return pair.substring(needle.length, pair.length);
        }
    }
    return null;
}

//Replacement for Window Onload - Loads before images, cross-browser
document.observe("dom:loaded", function () {
	//dynamicShadow('../images/global/shadow.png', 'page-container', 16, 0);
	liFirstLast(); // Adds classes 'first' and 'last' to respective LIs
	externalLinks();
	carousel();
	inputClear();
	heightBalance($$('section.category1 section'), 3);
	heightBalance($$('section.category2 section'), 3);
	heightBalance($$('section.category3 section'), 3);
	headerHelper();
	listSorter($$('ul.twoColumns'), 2);
	tabbedContent();
	addressPrefill();
	fontResizer();
	//stickyFooter();
});

// usage: log('inside coolFunc',this,arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
	log.history = log.history || [];   // store logs to an array for reference
	log.history.push(arguments);
	if(this.console){
		console.log( Array.prototype.slice.call(arguments) );
	}
};

// catch all document.write() calls
(function(doc){
	var write = doc.write;
	doc.write = function(q){
	log('document.write(): ',arguments);
		if (/docwriteregexwhitelist/.test(q)) write.apply(doc,arguments); 
	};
})(document);
