﻿var global = {
    cur_section : '',
    filtersArray : [],
    cur_page : '',
    cur_sub_page : '',
    news_filter  : false,
    cur_Item : '',
    cur_scroller : '',
	    
    setTopNav : function(){
        
        if(this.cur_page){
           $$('.cur_section').each(function(f){
		        if($(f).getParent().id == global.cur_page + "_link"){
		        
		            //Kill Tool Tip
		            $(f).getParent().getFirst().removeProperty('class');
		            $(f).getParent().getFirst().removeProperty('title');
		            $(f).getParent().getFirst().removeProperty('href');
		        	
		            //$(f).addClass('cur_section_selected');
									
					//swap image for 'selected section' nav item
					var cur_anchor = $(f).getParent().getElement('a');
					var cur_img = cur_anchor.getElement('img');
					var cur_img_src = cur_img.getProperty('src');
					var path_parts = cur_img_src.split('/');
					var cur_img_name;
					var new_img_name;
					var img_path = "";
					
					for(i=0; i<path_parts.length; i++) {
						if(i == path_parts.length-1) {
							cur_img_name = path_parts[i];
						} else if(i != 'undefined' && i != null && i != '') {
							img_path += "/" + path_parts[i];
						}
					}
					
					cur_img_name = cur_img_name.split('.');			
					cur_img_name[0] += '_on.';
					new_img_name = cur_img_name[0] + cur_img_name[1];
					
					cur_img.setProperty('src', img_path+'/'+new_img_name);
					
					//change text color to match swapped image
					 cur_anchor.getElement('span').getElement('p').addClass('selected_section');
		            
		            var curDescription  = $(f).getParent().getFirst().getFirst().alt.split(':');
		            $('section_title').setHTML(curDescription[0]);
		            $('section_discription').setHTML(curDescription[1]);
		        }
		        /*Remove un-wanted alt tags from DOM*/
		        $(f).getParent().getFirst().getFirst().setAttribute('alt','');
				
		    });
		   
		   //highlight sub nav
		   if(global.cur_page && global.cur_sub_page) {
		   		var subNavIdToMatch = global.cur_page + "_" + global.cur_sub_page;
				
				if($(subNavIdToMatch)) {
					$(subNavIdToMatch).addClass('selected_sub_section');
				}
				//specify link to select for news archive page, as in-page vars are different than other pages
				if(global.cur_sub_page == 'news_archive') {
					$(global.cur_sub_page).addClass('selected_sub_section');
				}
		   }
		   
		   //highlight sub nav (side) section
		   if(global.cur_page && global.section_nav_id) {
		   		var subSubNavIdToMatch = global.cur_page + "_" + global.cur_sub_page + "_" + global.section_nav_id;
				
				if($(subSubNavIdToMatch)) {
					$(subSubNavIdToMatch).addClass('selected_sub_sub_section');
				}
				
				/* append id to body tag for current page */
				var bodyTag = $$('body');
				bodyTag.setProperty('id', subSubNavIdToMatch);
		   }
		   
        }
        
        /* Set up Tool Tips IN Header */
        this.makeTips({x:-252,y:-110},'.header_link','header-tool');
        $$('.shareAccordion').setStyle('display','block');
		
		//PERFORM THE FOLLOWING FOR EVENTS SUB PAGES
		if(global.cur_page == "events" || global.cur_page == "news") {
			if($("section_overview")) $("section_overview").addClass('sub_nav_on');
			
		    //Create horizontal sub nav
			//Clone sub nav and move it into the correct place (header) and give it a new id
		    var curSubNavigation = $('sub_header_container');
			curSubNavigation.setStyle('display','block');
			curSubNavigation.setStyle('visibility','hidden');
			
			var cloneSubNav = curSubNavigation.clone().injectAfter('calendar_link');
			
		    cloneSubNav.setProperties({id: 'header_sub_nav_container'});
			curSubNavigation.remove(); //remove original sub nav
			
			global.setStyle('header_sub_nav_container', 'margin-left','17px');
			
			//hide nav during loading (scrambled on the screen during loading because of all the cloning going on)
			global.setStyle('header_sub_nav_container', 'visibility','hidden');
			//re-show nav after a couple of seconds (after it's been cloned and is in place)
			setTimeout("global.setStyle('header_sub_nav_container', 'visibility','visible')", 2000);
			
			//only re-show side nav on jamboree pages (but not for events overview page or news archive pages)
			if(global.cur_sub_page != "overview" && global.cur_sub_page != "news_archive") {
				setTimeout("global.setStyle('sub_header_container', 'visibility','visible')", 2000);
			}
			
			//Position sub nav differently for each page
			/*var curLink = global.cur_page+"_link";
			var navLeftOffset = 0;
			var curLinkLeftOffset = 0;
			
			curLinkLeftOffset = $(curLink).getLeft();
			navLeftOffset = $('experience_nav').getLeft();
			subnavX = curLinkLeftOffset - navLeftOffset;
			
			$('header_sub_nav_container').setStyle('margin-left',subnavX+'px');
				
			//hard-code sub nav width for ie
			if(global.cur_page == 'events') {
				//$('header_sub_nav_container').setStyle('width', '298px'); //if 3 menu items
				$('header_sub_nav_container').setStyle('width', '230px');
			} else if(global.cur_page == 'news') {
				$('header_sub_nav_container').setStyle('width', '150px');
			}*/
			
			//hide 'share' links put in header by .tpl
			//only need this for news page
			if(global.cur_page == "news") {
				if($('article_nav')) $('article_nav').setStyle('display', 'none');
			}
			
			//add arrow for sub nav
		    //var curSectionTab = global.cur_page + "_link";
			//if(curSectionTab) $(curSectionTab).setStyle('background','url("/shared/images/experience/sub_nav_at.gif") no-repeat bottom center');
					
			//remove extra sub section header
		    var curSubHeader = $('sub_section_overview');
			if(curSubHeader) curSubHeader.remove();
			
			//Move sub header into correct position
			//Clone and inject into new location, then remove the original
			var curSubHeader = $('sub_section_overview');
			if (curSubHeader) {
				var cloneSubHeader = curSubHeader.clone().injectAfter('experience_nav');
				curSubHeader.remove();
			}
			
			//add divider graphic under sub header
			if($('sub_section_title')) {
				var header_divider = new Asset.image('/shared/images/experience/exp_head_divider.jpg', {id: 'header_divider'});
				header_divider.injectAfter($('sub_section_title'));
			}
			
			
		} else {
			//FOR PAGES OUTSIDE EVENTS SUB PAGES, HIDE EXTRA SUB HEADER CONTAINER
			if($('sub_header_container')) {
				$('sub_header_container').setStyle('display','none');
			}
			
			if(global.cur_page != "calendar") {
				/* add id to body tag (except for calendar page, where id 'calendar' is already used on wrapper div */
				var bodyTag = $$('body');
				
				if(global.cur_sub_page != '') {
					bodyTag.setProperty('id', global.cur_page + "_" + global.cur_sub_page);
				} else {
					bodyTag.setProperty('id', global.cur_page);
				}
			}
			
		}
		
     },
	 
	 setStyle : function(el, key, value) {
		 $(el).setStyle(key,value);
	 },
	 
     setFooter : function(){
		 
        $('footer').setStyle('margin','0 auto');
        $('footer').setStyle('width','960px');
        $('logo_link_topper').setStyle('width','100%');
        $('disclaimer_link').setStyle('width','100%');
        
     },
     
  
    scrollBar : function(argScroll){
        $(argScroll).scroll = new Fx.Scroll($(argScroll+'_container'));
	    $(argScroll).scroll_container = $(argScroll+'_scrollarea');
	    $(argScroll).scroll_contents = $(argScroll+'_container');
	    $(argScroll).scroll_height = $(argScroll).scroll_container.getSize().size.y
	    $(argScroll).scroll_thumb = $(argScroll+'_scrollthumb');

	    $(argScroll).scroll_thumb_height = $(argScroll).scroll_thumb.getSize().size.y
	    $(argScroll).scroll_thumb.makeDraggable(
		    {
			    limit: {x: [0, 0], y: [0, $(argScroll).scroll_height - $(argScroll).scroll_thumb.getSize().size.y]},
			    onDrag:function(){
				    $(argScroll).percent_scrolled = ($(argScroll).scroll_thumb.getTop() - $(argScroll).scroll_container.getTop()) / ($(argScroll).scroll_height - $(argScroll).scroll_thumb_height);
				    $(argScroll).scroll_contents.setStyle('top', Math.round(0 - $(argScroll).scroll_height - (($(argScroll).scroll_contents.getSize().size.y - $(argScroll).scroll_height) * $(argScroll).percent_scrolled)) +'px');
			    }			
		    }
	    );
	    $(argScroll).scroll_thumb.setStyle('top',0);
	    $(argScroll).scroll_thumb.setStyle('left',0);
	
    },
    
    setScrollBar : function(){
        var item = global.cur_Item;
        var argScroll = global.cur_scroller;
        
        temp_y = item.getPosition().y - $(argScroll+'_container').getPosition().y;
		
        
	    if($(argScroll).scroll_contents.getSize().size.y >= $(argScroll).scroll_height){
		   global.moveScrollBar(argScroll,temp_y,400);
		   $(argScroll).scroll_container.setStyle('visibility', 'visible');
	    }else{
	       global.moveScrollBar(argScroll,temp_y,400);
	       $(argScroll).scroll_container.setStyle('visibility', 'hidden');
	    }
		
    },
    
    moveScrollBar: function(argScroll,argY,argDuration){
        temp_y = argY;

        var dest_y = (temp_y > $(argScroll).scroll_contents.getSize().size.y - $(argScroll).scroll_height) ? $(argScroll).scroll_contents.getSize().size.y - $(argScroll).scroll_height : temp_y;
        var percent_y = (temp_y > $(argScroll).scroll_contents.getSize().size.y - $(argScroll).scroll_height) ? 1 : temp_y / ($(argScroll).scroll_contents.getSize().size.y - $(argScroll).scroll_height);
		
        if($(argScroll).scroll_contents.getSize().size.y >= $(argScroll).scroll_height){
            var xTopScrollThumb = new Fx.Style($(argScroll).scroll_thumb, 'top', {duration:400,transition:Fx.Transitions.Sine.easeOut});
            xTopScrollThumb.start(Math.round(($(argScroll).scroll_height - $(argScroll).scroll_thumb.getSize().size.y) * percent_y));
        	    
            var xTopContents = new Fx.Style($(argScroll).scroll_contents, 'top', {duration:400,transition:Fx.Transitions.Sine.easeOut});
            xTopContents.start(Math.round(0 - $(argScroll).scroll_height - dest_y));
            
        }else{
            var xTopScrollThumb = new Fx.Style($(argScroll).scroll_thumb, 'top', {duration:400,transition:Fx.Transitions.Sine.easeOut});
            xTopScrollThumb.start(Math.round(($(argScroll).scroll_height - $(argScroll).scroll_thumb.getSize().size.y) * percent_y));
            
            var xTopContents = new Fx.Style($(argScroll).scroll_contents, 'top', {duration:400,transition:Fx.Transitions.Sine.easeOut});
            xTopContents.start(Math.round(0 - $(argScroll).scroll_height));
        }
        
   },
   
    moveSideScrollBar: function(argScroll,argY,argDuration){
        temp_y = argY;
		
		//from scrollBar function above:
	    $(argScroll).scroll_contents = $('upcomming_events');
		$(argScroll).scroll_height = $(argScroll).getSize().size.y
		
		//use sidebar_events div height in place of scrollarea div height, since we do not have a scrollarea div
        var dest_y = (temp_y > $(argScroll).scroll_contents.getSize().size.y - $(argScroll).scroll_height) ? $(argScroll).scroll_contents.getSize().size.y - $(argScroll).scroll_height : temp_y;

        if($(argScroll).scroll_contents.getSize().size.y >= $(argScroll).scroll_height){        	    
            var xTopContents = new Fx.Style($(argScroll).scroll_contents, 'top', {duration:400,transition:Fx.Transitions.Sine.easeOut});
            xTopContents.start(Math.round(0 - $(argScroll).scroll_height - dest_y));
            
        }else{            
            var xTopContents = new Fx.Style($(argScroll).scroll_contents, 'top', {duration:400,transition:Fx.Transitions.Sine.easeOut});
            xTopContents.start(Math.round(0 - $(argScroll).scroll_height));
        }
        
   },
   
   stopWindowScroll : function() {
		$$('body').addEvent('mousewheel', function(e){
			e = new Event(e);
			e.stop(); // prevent the mousewheel from scrolling the page
		});
	},
	
	/*enableWindowScroll : function() {
		console.log("enabling mouse wheel");
		$$('body').addEvent('mousewheel', function(e){
			e = new Event(e);
			//need a method here to re-enable the mouse wheel?
		});
	},*/
    
    setFilter : function(argFilter) {
		var optionFilter = argFilter;
		// if filter is set
		if (optionFilter != '' && optionFilter != 'undefined' && optionFilter != null) {
			// if the filter says to show everything, clear out the list of filters
			if (optionFilter == "all") {
				this.clearFilter();
			}
			else {
				this.toggleFilter(optionFilter);
			}
		}
	},
	
    toggleFilter : function(argFilter) {
		var isFilterActive = false;
		var filterIndex = "";
		var filterArrayCount = this.filtersArray.length;

		// Make sure some filters are set
		if (filterArrayCount != 0) {
			for (i = 0; filterArrayCount > i; i++) {
				// If the specified filter is in the array...
				if (argFilter == this.filtersArray[i]) {
					// set filter index
					isFilterActive = true;
					filterIndex = i;
				}
			}
		}

		// if showing all feed items...
		if (this.showAll) {
			// if no filters are set yet
			if (!isFilterActive) {
				// add new filter
				this.filtersArray.push(argFilter);
			}
			else {
				// Remove only this filter
				this.filtersArray.splice(filterIndex, 1);
			}
		}
		// if showing only some feed items...
		else {
			// if a filter is not set
			if (!isFilterActive) {
				this.filtersArray.push(argFilter); // add this filter
			}
		}
	},
	
	clearFilter : function() {
	    this.filtersArray = new Array(); 
	},
	
    makeTips : function(browserOffset,eleClass,tipClassName){
        //if (window.ie6 || navigator.appVersion.indexOf("Mac")!=-1){
		if (window.ie || navigator.appVersion.indexOf("Mac")!=-1){
            var HeaderTips = new Tips($$(eleClass), {className: tipClassName,offsets: browserOffset});
        }else{
             var HeaderTips = new Tips($$(eleClass), {
             className: tipClassName,
             offsets: browserOffset,
             initialize:function(){
             this.fx = new Fx.Style(this.toolTip, 'opacity', {duration: 500, wait: false}).set(0);},
             onShow: function(toolTip) {this.fx.start(1);},
             onHide: function(toolTip) {this.fx.start(0);}});
        }
    },
    
    initAccordion : function(name, content_selector, toggler_selector, argShow, argAlwaysHide, myFunction) {
		// -1 is the default don't-show-anything value
		argShow = argShow ? 0 : -1;
		
		argAlwaysHide = argAlwaysHide || false;
		myFunction = myFunction || function() {};
		
		
        //Create accordion object if it doesn't exist
        if(typeof(accordions) != 'object') {
            accordions = [];
        }
        
        //Create a single accordion control, including empty objects and properties
        accordions[name] = new global.newAccordion()
        acc = accordions[name];
        
        //Define the content items of the accordion
        acc.content = $$(content_selector);
	    acc.content.each(function(item){
		    item.setStyles({'height': '0', 'overflow': 'hidden'}); //THIS IS WHERE EVENTS ITEMS GET THEIR INITIAL HEIGHT
	    });

	    //Define the togglers of the accordion
	    acc.togglers = $$(toggler_selector);
	    this.setTogglerEvents(name,acc.togglers);
	
		acc.myAccordion = new Fx.Accordion(acc.togglers, acc.content, {display: argShow, alwaysHide: argAlwaysHide, opacity: false, start: false, transition: Fx.Transitions.quadOut, wait: false, onComplete:eval(myFunction)});
    },
	
    setTogglerEvents : function(name, toggler){
         var curItem = "";
         
         if (name == 'events') {
		    var curItem = '';
			
		    toggler.each(function(item) {
				
			    item.addEvent('click', function() {
				    if (this != curItem) {
					    item.addClass('open');
					    item.getNext().addClass('open');
						//item.setStyle('border', 'solid 1px red');
						
					    //Scrollbar stuff
					    global.cur_Item = item;
                        global.cur_scroller = 'events';
                        
					    if(curItem != ''){
					        curItem.removeClass('open');
					        curItem.getNext().removeClass('open');
					    }
										
						//find list overlap
						//use delay to get height after event is loaded in
						//setTimeout("global.moveSideScrollBar('"+item+"')",3000);
						//setTimeout("global.moveSideScrollBar()",3000);
						
					    curItem = this;
				    }
					
			    });

			    item.addEvent('mouseenter', function() {
				    item.addClass('hover');
			    });

			    item.addEvent('mouseleave', function() {
				    item.removeClass('hover');
			    });
		    });
	    }
		
		if (name == 'jamboree_events') {
	        var curItem = '';
			var bonus_space = 0;
			var cur_id_num = -1;
			
	        toggler.each(function(item) {
			    
		        item.addEvent('click', function() {
		        
		            item.removeClass('open');
				    item.getNext().removeClass('open');
				    
			        if (this != curItem) {
				        item.addClass('open');
				        item.getNext().addClass('open');
					    //item.setStyle('border', 'solid 1px red');
						
				        //Scrollbar stuff
				        global.cur_Item = item;
                        global.cur_scroller = 'events';
                        
				        if(curItem != ''){
				            cur_id_num = curItem.id.replace('event_', '');
				            curItem.removeClass('open');
				            curItem.getNext().removeClass('open');
				        }
				        
				        var item_id_num = item.id.replace('event_', '');
				        
				        if(parseInt(cur_id_num) < parseInt(item_id_num) && cur_id_num != -1){
				            bonus_space = curItem.getNext().getSize().size.y;
				        }else{
				            bonus_space = 0;
				        }
				        
				        curItem = this;
				        
			        }else{
			            curItem = '';
			            global.cur_Item = '';
			            cur_id_num = -1;
			            bonus_space = 0;
			        }
					
					//Use delay to get height after event is loaded in
					setTimeout("events.setSideScrollBar(" + item.getCoordinates().top + "," + bonus_space + ")",500);
		        });

		        item.addEvent('mouseenter', function() {
			        item.addClass('hover');
		        });

		        item.addEvent('mouseleave', function() {
			        item.removeClass('hover');
		        });
	        });
	     }
	    
         if(name == "share"){
	            toggler.each(function(item){
                var isOpen = false;
                    item.addEvent('click', function(){
                        isOpen ? isOpen = false:isOpen = true;
                        isOpen ? item.setHTML('CLOSE'):item.setHTML('Share w/Jeep');
                        isOpen ? item.removeClass('shareToggler'):item.addClass('shareToggler');
                        isOpen ? item.addClass('shareToggler_open'):item.removeClass('shareToggler_open');
                    });
					
               });
	        }
	        
	        if(name == 'tags') {
			   acc.togglers.each(function(item) {

				
				curItem = "";

				item.addEvent('click', function(){
					//Turn off default link

					if(curItem != ""){
						curItem.removeClass('item_at');
						curItem.addClass('item');
					}

					if(this != curItem){
						//Turn on current
						item.removeClass('item');
						item.removeClass('item_on');
						item.addClass('item_at');
						curItem = this;
					}else{
						item.removeClass('item_at');
						item.addClass('item');
						curItem = "";
					}

				});

				item.addEvent('mouseenter', function(){
					if(curItem != this){
						item.removeClass('item');
						item.addClass('item_on');
					}
				});

				item.addEvent('mouseleave', function(){
					if(curItem != this){
						item.removeClass('item_on');
						item.addClass('item');
					}else{
						item.removeClass('item_on');
						item.addClass('item_at');
					}
				});

			});
		}
	        
         if(name == "swag"){
            acc.togglers.each(function(item){
               
                 //item.getParent().getFirst().removeClass('item');
                 //item.getParent().getFirst().addClass('item_at');
                 curItem = "";
                
                item.addEvent('click', function(){
                     //Turn off default link
                     
                     if(curItem != ""){
                         curItem.removeClass('item_at');
                         curItem.addClass('item');
                     }
                     
                     if(this != curItem){
                         //Turn on current
                         item.removeClass('item');
                         item.removeClass('item_on');
                         item.addClass('item_at');
                         curItem = this;
                     }else{
                        item.removeClass('item_at');
                        item.addClass('item');
                        curItem = "";
                     }
                    
                });
                
                item.addEvent('mouseenter', function(){
                    if(curItem != this){
	                   item.removeClass('item');
                       item.addClass('item_on');
	                }
                 });
                
                item.addEvent('mouseleave', function(){
                    if(curItem != this){
                         item.removeClass('item_on');
                         item.addClass('item');
	                }else{
                          item.removeClass('item_on');
                          item.addClass('item_at');
	                }
                 });
          
           });
         }
         
        if(name == "feed_accordions"){
            
             acc.togglers.each(function(item){
               
                 item.getParent().getFirst().removeClass('news_item');
                 item.getParent().getFirst().addClass('news_item_at');
                 curItem = item.getParent().getFirst();
                
                item.addEvent('click', function(){
                     //Turn off default link
                     curItem.removeClass('news_item_at');
                     curItem.addClass('news_item');
                     
                     //Turn on current
                     item.removeClass('news_item');
                     item.removeClass('news_item_on');
                     item.addClass('news_item_at');
                     curItem = this;
                });
                
                item.addEvent('mouseenter', function(){
                    if(curItem != this){
		               item.removeClass('news_item');
                       item.addClass('news_item_on');
		            }
                 });
                
                item.addEvent('mouseleave', function(){
                    if(curItem != this){
	                     item.removeClass('news_item_on');
                         item.addClass('news_item');
		            }else{
                          item.removeClass('news_item_on');
                          item.addClass('news_item_at');
		            }
                 });
          
           });
	    }
    },
    
    newAccordion : function(name) {
        //Create an empty object to hold accordion properties
        this.content = [];
        this.togglers = [];
    }
}

function matchColumnHeight(classes) {
	// Set the columns to the same height	
	var columns = $$(classes);
	
	columns.each(function(elt) {
		var curHeight = elt.getSize().size.y;
		if (curHeight > maxHeight) maxHeight = curHeight;
	});
	
	columns.each(function(elt) {
	 if(elt.getElement('ul')){
		elt.getElement('ul').setStyle('height', maxHeight+'px');
	 }
	});

}

function assignTarget(id, clss) {
	var anchors = $(id).getElements('a.' + clss);
	
	anchors.each( function(anchor) {
		anchor.setProperty('target', '_blank');
	});
}

function ie6WidthFix(){
  var wrapperWidth = $('wrapper').getSize().size.x;
  var windowWidth = window.getSize().size.x;
  
  if(windowWidth <= 960){
    $('wrapper').setStyle('width','960px');
  }else{
    $('wrapper').setStyle('width','100%');
  }
  
}

var maxHeight = 0;

onload_register('global.setFilter(global.cur_page)');
onload_register('global.setTopNav()');
onload_register('global.setFooter()');

//IE 6 Tweaks.
if (window.ie6){
    onload_register('iePngFix();');
    onload_register('ie6WidthFix();');
    onload_register('window.onresize = ie6WidthFix;');
}


 