$(function(){
	$('li.tlevel:last-child').addClass('lastitem');
	//$('.menu li').children('ul').parent().addClass('sub');
	$('li.lastitem li.slevel li.thlevel').closest('ul').addClass('left');
	$('li.lastitem li.slevel li.frtlevel').closest('ul').addClass('left');
	$('li.lastitem li.slevel li.fftlevel').closest('ul').addClass('left');
});
function ieFix(topLevel) 
{
var ua = navigator.userAgent;
var isMSIE = (navigator.appName == "Microsoft Internet Explorer");
var isMSIE5_5 = isMSIE && (ua.indexOf('MSIE 5.5') != -1);
var isMSIE6 = isMSIE && (ua.indexOf('MSIE 6.0') != -1);

	if (isMSIE5_5 || isMSIE6) 
	{
	document.getElementById(topLevel).innerHTML = document.getElementById(topLevel).innerHTML.replace (/<ul/gi,"<table><tr><td><ul").replace (/<\/ul>/gi,"</ul></td></tr></table></a>");
	for (i=0;i<document.getElementsByTagName("li").length; i++) 
		{
		if (document.getElementsByTagName("li").item(i).className == "sub")
			{
			document.getElementsByTagName("li").item(i).innerHTML = document.getElementsByTagName("li").item(i).innerHTML.replace(/<\/a>/i,"");
			}
		}
	}
}

/*$(function() {
	var zIndexNumber = 1000;
	$('div').each(function() {
		$(this).css('zIndex', zIndexNumber);
		zIndexNumber -= 10;
	});
	$('div.leftbg').css('z-index','1');
	$('div.logo').css('z-index','1');
	$('div.glidecontenttoggler').css('z-index','999');
});*/

//Featured Content Glider: By http://www.dynamicdrive.com
//Created: Dec 22nd, 07'
//Updated (Jan 29th, 08): Added four possible slide directions: "updown", "downup", "leftright", or "rightleft"
//Updated (Feb 1st, 08): Changed glide behavior to reverse direction when previous button is clicked
//Updated (Feb 12th, 08): Added ability to retrieve gliding contents from an external file using Ajax ("remotecontent" variable added to configuration)
//Updated (July 21st, 09): Updated to work in jQuery 1.3.x

//jQuery.noConflict()

/*var featuredcontentglider2={
	csszindex: 100,
	ajaxloadingmsg: '<b>Fetching Content. Please wait...</b>',
	glide:function(config, showpage, isprev){
		var selected=parseInt(showpage)
		if (selected>=config.$contentdivs.length){ //if no content exists at this index position
			//alert("No content exists at page "+(selected+1)+"! Loading 1st page instead.")
			selected=0
		}
		var $target=config.$contentdivs.eq(selected)
		//Test for toggler not being initialized yet, or user clicks on the currently selected page):
		if (config.$togglerdiv.attr('lastselected')==null || parseInt(config.$togglerdiv.attr('lastselected'))!=selected){
			if ($('#innernav').css("left") == "0px" || $('#innernav').css("left") == "auto") {
				var $selectedlink=config.$toc.eq(selected)
				if ($($($selectedlink).parent()).html() == $('.glideitem:first').html()) {
					isprev="previous";
				}
				config.$next.attr('loadpage', (selected<config.$contentdivs.length-1)? selected+1+'pg' : 0+'pg')
				config.$prev.attr('loadpage', (selected==0)? config.$contentdivs.length-1+'pg' : selected-1+'pg')
				var startpoint=(isprev=="previous")? -config.startpoint : config.startpoint
				$target.css(config.leftortop, startpoint).css("zIndex", this.csszindex++) //hide content so it's just out of view before animating it
				var endpoint=(config.leftortop=="left")? {left:0} : {top:0} //animate it into view
				$target.hide();
				$target.css("left","0");
				$target.fadeIn('slow');
				//$target.animate(endpoint, config.speed)
				var notfirst = false;
				//if (config.$togglerdiv.attr('lastselected')!=null) {
				if (isprev=="previous") {
					featuredcontentglider2.movecontentback(config, showpage, isprev, $selectedlink, selected);
				} else {
					featuredcontentglider2.movecontentforward(config, showpage, isprev, $selectedlink, selected);
				}
			}
		}
	},

	movecontentback:function(config, showpage, isprev, $selectedlink, selected){
		//$('#innernav .glideitem:first').before("<div class='glideitem' style='display:none'></div>");
		//$('#innernav .glideitem:first').html($('.glideitem:last a').clone());
		//$('#innernav .glideitem:first').show();
		//$('#innernav').css("left","-61px");
		//$('#innernav').stop().animate({"left":"+=61px"}, "slow",function(){
			//$('#innernav .glideitem:first').html($('#innernav .glideitem:last a'));
			//$('#innernav .glideitem:last').remove();
			config.$toc.removeClass('selected');  //remove selected from all thumbs
			$selectedlink.addClass('selected');   //add selected to current thumb
			config.$togglerdiv.attr('lastselected', selected+'pg');
		//});
	},
	
	movecontentforward:function(config, showpage, isprev,$selectedlink, selected){
		config.$toc.removeClass('selected');  //remove selected from all thumbs
		$selectedlink.addClass('selected');   //add selected to current thumb
		if (config.$togglerdiv.attr('lastselected')!=null) {
			//$('#innernav').append("<div class='glideitem'></div>");
			//$('#innernav .glideitem:last').append($('.glideitem:first a').clone());
			//$('#innernav').stop().animate({"left":"-=61px"}, "slow", function(){
				//$('#innernav .glideitem:last').html($('#innernav .glideitem:first a'));
				//$(this).css("left","0px");
				//$('#innernav .glideitem:first').remove();
			//});
		}
		config.$togglerdiv.attr('lastselected', selected+'pg');
	},
	
	getremotecontent:function($, config){
		config.$glider.html(this.ajaxloadingmsg)
		$.ajax({
			url: config.remotecontent,
			error:function(ajaxrequest){
				config.$glider.html('Error fetching content.<br />Server Response: '+ajaxrequest.responseText)
			},
			success:function(content){
				config.$glider.html(content)
				featuredcontentglider2.setuptoggler($, config)
			}
		})
	},

	aligncontents:function($, config){
		config.$contentdivs=$("#"+config.gliderid+" ."+config.contentclass)
		config.$contentdivs.css(config.leftortop, config.startpoint).css({height: config.$glider.height(), visibility: 'visible'}) //position content divs so they're out of view:
	},

	setuptoggler:function($, config){
		this.aligncontents($, config)
		config.$togglerdiv.hide()
		config.$toc.each(function(index){
				$(this).attr('pagenumber', index+'pg')
				if (index > (config.$contentdivs.length-1))
					$(this).css({display: 'none'}) //hide redundant "toc" links
		})
		var $nextandprev=$("#"+config.togglerid+" .next, #"+config.togglerid+" .prev")
		$nextandprev.click(function(event){ //Assign click behavior to 'next' and 'prev' links
			featuredcontentglider2.glide(config, this.getAttribute('loadpage'), this.getAttribute('buttontype'))
			event.preventDefault() //cancel default link action
		})
		config.$toc.click(function(event){ //Assign click behavior to 'toc' links
			featuredcontentglider2.glide(config, this.getAttribute('pagenumber'))
			event.preventDefault()
		})
		config.$togglerdiv.fadeIn(1000, function(){
			featuredcontentglider2.glide(config, config.selected)
			if (config.autorotate==true){ //auto rotate contents?
				config.stepcount=0 //set steps taken
				config.totalsteps=config.$contentdivs.length*config.autorotateconfig[1] //Total steps limit: num of contents x num of user specified cycles)
				featuredcontentglider2.autorotate(config)
			}
		})
		config.$togglerdiv.click(function(){
			featuredcontentglider2.cancelautorotate(config.togglerid)
		})
	},

	autorotate:function(config){
		var rotatespeed=config.speed+config.autorotateconfig[0]
		window[config.togglerid+"timer"]=setInterval(function(){
			if (config.totalsteps>0 && config.stepcount>=config.totalsteps){
				clearInterval(window[config.togglerid+"timer"])
			}
			else{
				config.$next.triggerHandler('click')
				config.stepcount++
			}
		}, rotatespeed)
	},

	cancelautorotate:function(togglerid){
		if (window[togglerid+"timer"])
			clearInterval(window[togglerid+"timer"])
	},

	getCookie:function(Name){ 
		var re=new RegExp(Name+"=[^;]+", "i") //construct RE to search for target name/value pair
		if (document.cookie.match(re)) //if cookie found
			return document.cookie.match(re)[0].split("=")[1] //return its value
		return null
	},

	setCookie:function(name, value){
		document.cookie = name+"="+value
	},

	init:function(config){
		jQuery(document).ready(function($){
			config.$glider=$("#"+config.gliderid)
			config.$togglerdiv=$("#"+config.togglerid)
			config.$toc=config.$togglerdiv.find('.toc')
			config.$next=config.$togglerdiv.find('.next')
			config.$prev=config.$togglerdiv.find('.prev')
			config.$prev.attr('buttontype', 'previous')
			var selected=(config.persiststate)? featuredcontentglider2.getCookie(config.gliderid) : config.selected
			config.selected=(isNaN(parseInt(selected))) ? config.selected : selected //test for cookie value containing null (1st page load) or "undefined" string	
			config.leftortop=(/up/i.test(config.direction))? "top" : "left" //set which CSS property to manipulate based on "direction"
			config.heightorwidth=(/up/i.test(config.direction))? config.$glider.height() : config.$glider.width() //Get glider height or width based on "direction"
			config.startpoint=(/^(left|up)/i.test(config.direction))? -config.heightorwidth : config.heightorwidth //set initial position of contents based on "direction"
			if (typeof config.remotecontent!="undefined" && config.remotecontent.length>0)
				featuredcontentglider2.getremotecontent($, config)
			else
				featuredcontentglider2.setuptoggler($, config)
			$(window).bind('unload', function(){ //clean up and persist
				config.$togglerdiv.unbind('click')
				config.$toc.unbind('click')
				config.$next.unbind('click')
				config.$prev.unbind('click')
				if (config.persiststate)
					featuredcontentglider2.setCookie(config.gliderid, config.$togglerdiv.attr('lastselected'))
				config=null
				
			})
		})
	}
}

function buildImageList() {
	$('#slide_viewer').html("Loading...<img src='/atf/cf/{aa054551-9f6f-400f-8684-a92f49708887}/loading.gif' />");	
	$.get("/c.dmJXKiOYJgI6G/b.6328539/k.943E/Feature_Carousel/siteapps/tools/PhotoGallery.aspx",function(data){
		var html = '';
		var htmltoc = '<a href="#" class="prev"></a><div id="outernav"><div id="innernav">';
		$(data).find('#pg_summary img').each(function(i){
			var imgsrc = $(this).attr("src");
			html += "<div class='glidecontent'><div class='glideimage'><a href='"+$(data).find('#pg_summary .pg_shortdescriptor:eq('+i+')').html().replace("&nbsp;","")+"#'><img src='"+imgsrc+"' border=0/></a></div>";
			html += "	<div class='slide_info'><div class='slide_title'>"+$(data).find('#pg_summary .pg_title:eq('+i+')').html()+"</div>"+"<div class='slide_description'>"+$(data).find('#pg_summary .pg_longdescriptor:eq('+i+')').html()+"</div></div>";
			html += '</div>';
			//htmltoc += '<div class="glideitem"><a href="#" class="toc">'+(i+1)+'</a></div>';
		});
		htmltoc += '</div></div><div id="toc-blocks"><a href="#" class="toc">1</a> <a href="#" class="toc">2</a> <a href="#" class="toc">3</a> <a href="#" class="toc">4</a> <a href="#" class="toc">5</a></div><a href="#" class="next"></a>';
		$('#slide_viewer').html(html);	
		$('.glidecontenttoggler').html(htmltoc);
		featuredcontentglider2.init({
			gliderid: "slide_viewer", //ID of main glider container
			contentclass: "glidecontent", //Shared CSS class name of each glider content
			togglerid: "p-select", //ID of toggler container	
			remotecontent: "", //Get gliding contents from external file on server? "filename" or "" to disable
			selected: 0, //Default selected content index (0=1st)
			persiststate: false, //Remember last content shown within browser session (true/false)?
			speed: 500, //Glide animation duration (in milliseconds)
			direction: "rightleft", //set direction of glide: "updown", "downup", "leftright", or "rightleft"
			autorotate: true, //Auto rotate contents (true/false)?
			autorotateconfig: [6000, 10] //if auto rotate enabled, set [milliseconds_btw_rotations, cycles_before_stopping]
		});
	});
}*/


/* Maps */
(function($) {
	$.fn.zoommap = function(settings) {
		settings = $.extend({
			zoomDuration: 1000,
			zoomClass: 'zoomable',
			popupSelector: 'div.popup',
			popupCloseSelector: 'a.close',
			bulletWidthOffset: '10px',
			bulletHeightOffset: '10px',
			showReturnLink: true,
			returnId: 'returnlink',
			returnText: 'Return to Previous Map'
		}, settings);
		
		$(this).each(function(){
			var map = $(this);
			$(this).data('currentId', '');
			
			function showMapById(id){
				var region = findRegion(settings.map, id);
				if(region != -1){
					displayMap(region);
				}
			}

			// recursive id find
			function findRegion(root, id){
				if(root.id == id){
					return root;
				}else{
					if(root.maps != undefined){
						for(var i=0; i<root.maps.length; i++){
							var possible = findRegion(root.maps[i], id);
							if(possible != -1)
								return possible;
						}
					}
				}
				return -1;
			}
			
			// region is a map
			// This gets called every time we zoom
			function displayMap(region){
				//Set Current Region Id
				$(this).data('currentId', region.id);
				
				//Clear the Map and Set the Background Image
				map.empty().css({
					backgroundImage: 'url(' + region.image + ')',
					width: settings.width,
					height: settings.height
				});
				var check = map.css('background-image');
				
				//Load RegionData
				loadRegionData(region);
			}
			/************************************************************************************/

			
			//Show Return Link
			function showReturnLink(region){
				map.append('<a href="javascript:void(0);" id="' + settings.returnId + '">' + settings.returnText + '</a>');
				$('#' + settings.returnId).hide().fadeIn().click(function(){
					showMapById(region.parent);
				});
			}
				
			
			//Load the Bullets 
			function loadRegionData(region){
				var url = region.data;
				$.get(url, function(mapdata){
					map.append(mapdata);
					//place bullets
					map.children('a.bullet, a.bullet-gray').each(function(){
						var coords = $(this).attr('rel').split('-');
						$(this).css({left: addpx(Number(coords[0]) - rempx(settings.bulletWidthOffset)), top: addpx(Number(coords[1]) - rempx(settings.bulletHeightOffset))})
							   .hide()
							   .click(function(){showPopup($(this).attr('id'));})
							   .fadeIn('fast');							
					});
					//Set up each submap as an item to click
					if(region.maps != undefined){
						for(var i=0; i<region.maps.length; i++){
							addZoom(region.maps[i]);
						}
					}
					//Create Return Link
					if(settings.showReturnLink && region.parent != undefined){
						showReturnLink(region);
					}						
				});
			}
			
			function showPopup(id, leftbul, topbul){
				map.find(settings.popupSelector).fadeOut();
				$('#mapline').remove(); 
				var boxid = '#' + id + '-box';
				topbul = 0;
				var topbullet = topbul;
				leftbul = 0;
				var leftbullet = leftbul;
				$(boxid).css("top",topbullet);
				$(boxid).css("left",leftbullet);
				
				$(boxid).fadeIn();
				topbul = parseInt(topbul)+20;
				leftbul = parseInt(leftbul)+20;
				// map.append("<img src='/atf/cf/{3F934D1F-3443-49CB-95AC-954E18EF5D03}/mapline.png' id='mapline' style='position:absolute;top:"+topbul+"px;left:"+leftbul+"px'/>");  ORIGINAL CODE
				
				$(settings.popupCloseSelector).click(function(){
					$('#mapline').remove();
					$(this).parent().fadeOut();
				});
			}
			
			//add a clickable image for a region on the current map
			function addZoom(region){
				$('<img />').addClass(settings.zoomClass)
					.attr({
						src: settings.blankImage,
						id: region.id
					}).css({
						position: 'absolute',
						width: region.width,
						height: region.height,
						top: region.top,
						left: region.left,
						cursor: 'pointer'
					}).appendTo(map).click(function(){
						//hide neighboring bullets and zoomables
						var width = settings.width;
						var height = settings.height;
						if(region.scan){
							width = region.scanwidth;
							height = region.scanheight;
						}
						$(this).siblings().fadeOut();
						$(this).hide()
							   .attr('src', region.image).load(function(){
									$(this).fadeIn('slow')
										   .animate({
												width: width,
												height: height,
												top: '0px',
												left: '0px'
											}, settings.zoomDuration, '', function(){
												displayMap(region);
											});
								});
					});
			}
			
			function rempx(string){
				return Number(string.substring(0, (string.length - 2)));
			}
			
			function addpx(string){
				return string + 'px';
			}
			
			function showHash(string){
				string = string.replace('#', '');
				showMapById(string);
			}
			
			//initialize map
			var hash = self.document.location.hash;
			if(hash.length > 0)
				showHash(hash);
			else{
				displayMap(settings.map);
			}
			
			return this;
		});
	}
})(jQuery);


//Newsletter Populate Script
var urlTest = new RegExp("^(ht|f)tp(s?)\:\/\/(([a-zA-Z0-9\-\._]+(\.[a-zA-Z0-9\-\._]+)+)|localhost)(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)?([\d\w\.\/\%\+\-\=\&amp;\?\:\\\&quot;\'\,\|\~\;]*)$");

function populate(form)
{
    if ( location.search == null || location.search.length < 1 ) return; // no querystring

    var pairs = location.search.substring(1).split("&");
    for ( var p = 0; p < pairs.length; ++p )
    {
        var pair = pairs[p].split("=");
        var name = pair[0];
        var value = unescape( pair[1].replace(/\+/g, " ") );
        var fld = form.elements[name];
        var ftype = null;
        var farray = false;
        var atype = Array;

        if ( fld != null )
        {
            if ( fld.length != null && fld.length >= 1 && fld[0].type != null && fld[0].type != undefined )
            {
                ftype = fld[0].type;             
                farray = true;
            } else {
                ftype = fld.type;
            }
        }
        switch ( ftype )
        {
            case "text": case "hidden": case "textarea":
                if ( farray ) fld = fld[0]; // only handle first-named for this type
                fld.value = value;
                break;
            case "select-one": case "select-multiple":
                if ( farray ) fld = fld[0]; // only handle first-named for this type
                for ( var o = 0; o < fld.options.length; ++o )
                {
                    var opt = fld.options[o];
                    var oval = opt.value;
                    if ( oval == null || oval == "" ) oval = opt.text;
                    if ( oval == value )
                    {
                        opt.selected = true;
                        break;
                    }
                }
                break;
            case "checkbox": case "radio":
                if ( ! farray )
                {
                    // single checbox or radio of that name:
                    fld.checked = true;
                } else {
                    for ( var cr = 0; cr < fld.length; ++cr )
                    {
                        if ( fld[cr].value == value )
                        {
                            fld[cr].checked = true;
                            break;
                        }
                    }
                }
                break;
            default:
                alert("Unknown field type encountered for field " + name + ": " + ftype);
                break;
        } // end of switch
    } // end of loop on fields from qs
}

function doClear(theText) {
     if (theText.value == theText.defaultValue) {
         theText.value = ""
     }
 }

// Onload Events
$(document).ready(function() {
   if ($('#search').length > 0) {
	   $('#search .submit').hover(function(){
			$(this).parent().parent().css('background-position','0 -129px');
	   },function(){
			$(this).parent().parent().css('background-position','0 -107px');
	   });
   }
   if ($('#newsletter').length > 0) {
	   $('#newsletter .submit').hover(function(){
			$(this).css('background-position','-116px -68px');
	   },function(){
			$(this).css('background-position','-7px -68px');
	   });
   }
   
   if ($("ul.tabs").length > 0) $("ul.tabs").tabs("div.panes > div");

   if (document.SUPPORTER447487) populate(document.SUPPORTER447487);
   
   $('input[name=first_name], input[name=last_name], input[name=address_line_1], input[name=address_line_2]').blur(function(){
		if ($(this).val().match(urlTest)) {
		   alert("Value entered is invalid. Please re-enter");
		   setFocus(this);
		   return;
		}
	});
});

function setFocus(id) {
	setTimeout(function(){$(id).focus();},50);
}

// Custom Fair Trade Tabs -- Added by Dan Ruth, Sep 7, 2011

	//$(function() {
		///$( "#tabs" ).tabs();
	//});

