var base_url = document.location.protocol + '//' + document.location.host + '/';
var theme_url = base_url + 'themes/rmhc';
var img_url = theme_url + '/img';
var swf_url = theme_url + '/swf';
var swf_video_url = swf_url + '/videoplayer_assets';
var country_xml_url = base_url + 'what-we-do/local-chapters-at-work/xml/';
var express_install = swf_url + '/expressInstall.swf';
var rmhc = null;


(function($) {

	var RMHC = window.RMHC = {
	    init : function() {
	        var express_install = swf_url + '/expressInstall.swf';
	
	        RMHC.sifr.init();
	
	        var img = new Image();
	        img.src = img_url + '/header/dropdown.png';
	
	        RMHC.home.init();
	        RMHC.stories.init();
	        RMHC.list_to_blinds(jQuery('ul.faq'));
	        RMHC.dropdown.init();
	        RMHC.search.init();
			RMHC.youtube.init();
			RMHC.click_tracker();
			rmhc = RMHC;
	    },
	
	    sifr : {
	        init : function() {
	            if (typeof sIFR == "function") {
	                sIFR.replaceElement(".sifr", named({
	                    sFlashSrc: swf_url + '/archer-semibold.swf',
	                    sColor: "#8a0000",
	                    sWmode: "transparent"
	                }));
	            }
	        }
	    },
		
		youtube : {
			watchText: 'Watch Video',
			hideText: 'Hide Video',
			
			init : function() {
				var me = RMHC.youtube;
				
				$('object.youtube-plugin').before('<a href="#" class="youtube-watch">' + me.watchText + '</a>').hide();
				$('.youtube-watch').click(function() {
					var link = $(this);
					
					if (link.hasClass('visible')) {
						link.removeClass('visible').html(me.watchText);
						link.next().hide();
					} else {
						link.addClass('visible').html(me.hideText);
						link.next().show();
					}
					return false;
				});
			}
		},
	
	    home : {
	        init : function() {
	            /*if (jQuery('#homepage_video').get(0)) {
	                
	                RMHC.home.embedVideoSwf();
	            }*/
			
			if (jQuery('#homepage_video').get(0))
			{
				if (!RMHC.home.getVideoIdFromHash())
					RMHC.home.embedVolSwf();
				else
					RMHC.home.embedVideoSwf();
			}
				
				RMHC.home.initReloadLinks();
	        },
			
			initReloadLinks : function() {
				$('ul.features a[href^=/#], .load-video, a[rel=video]').click(function(event) {
					var wrap = $('#content-wrapper').position();
					$('html, body').animate({scrollTop: wrap.top + 'px'}, 500);
					$('#homepage_video').replaceWith('<img id="homepage_video" src="themes/rmhc/img/home/video.jpg" />');
			
					RMHC.home.embedVideoSwf(this.href);
					return false;
				});
			},
			
			embedVolSwf : function() {
				var flashvars = {};
				//For the volunteer month campaign
				swfobject.embedSWF(swf_url + '/Preloader.swf', 'homepage_video', '930', '359', '8.0.0', express_install, flashvars, { wmode: 'opaque' });
			},
			
			embedVideoSwf: function(vidHref) {
				var flashvars = {};
				
				var videoId = RMHC.home.getVideoIdFromHash(vidHref);
				if (videoId !== false) {
					flashvars.startup_id = videoId;
				}
				flashvars.videoassets_url = swf_video_url + '/';
				swfobject.embedSWF(swf_url + '/rmhc_baseflash.swf', 'homepage_video', '930', '359', '8.0.0', express_install, flashvars, { wmode: 'opaque' });	
			},
			
			getVideoIdFromHash: function(hash) {
				hash = hash || document.location.hash;
				if (hash) {
	                var matches = hash.match(/#video\-([0-9]+)$/);
	                if (matches) {
	                    return matches[1];
	                }
	            }
				
				return false;
			}
	    },
	
	    search : {
	    	init : function()
	    	{
	    		var input = jQuery("form[name='search_form'] input[name='s']");
	
	    		input.bind('focus', function(e)
	    		{
	    			if (!jQuery(this).attr('visited'))
	    				this.value = '';
	
	    			jQuery(this).attr('visited', true);
	    		});
	
	    		input.bind('blur', function(e)
	    		{
	    			if (this.value == '')
	    			{
	    				this.value = 'Search';
	    				jQuery(this).removeAttr('visited');
	    			}
	    		});
	    	}
	    },
	
	    dropdown : {
	        init : function() {
	    		var mainNavAnchors = jQuery('ul#nav-main li.level-1 a.level-1');
	    		mainNavAnchors.bind('mouseover', RMHC.dropdown.anchorHover);
	    		mainNavAnchors.bind('mouseout', RMHC.dropdown.anchorHoverOut);
	
	    		var menus = jQuery('ul#nav-main li.level-1 ul.dropdown');
	            menus.mouseover(RMHC.dropdown.menuHover)
	                .mouseout(RMHC.dropdown.menuHoverOut);
	            jQuery('a', menus).mouseover(function() {
	                RMHC.dropdown.clearTimer(jQuery(this).parents('ul.dropdown'));
	            });
	        },
	
	        clearTimer: function(menu)
	        {
	        	if (menu.attr('closingTimer'))
	        	{
	        		window.clearTimeout(menu.attr('closingTimer'));
	        		menu.removeAttr('closingTimer');
	        	}
	        },
	
	        setTimerToHideMenu: function(menu)
	        {
	        	RMHC.dropdown.clearTimer(menu);
	
	        	var timeoutValue = 300;
	
	        	if (arguments[1])
	        		timeoutValue = arguments[1];
	
		    	var timeout = window.setTimeout(function()
		    	{
		    		menu.hide();
		    		menu.removeAttr('closingTimer');
		    	},
		    	timeoutValue);
	
		    	menu.attr('closingTimer', timeout);
	        },
	
	        anchorHover: function(event)
	    	{
	            jQuery('#nav-main ul.dropdown').hide();
	        	var mainAnchor = jQuery(event.target);
	        	var menu = mainAnchor.next('ul.dropdown');
	        	//menu.slideDown(500);
	        	menu.show();
	        	RMHC.dropdown.clearTimer(menu);
	    	},
	
	    	anchorHoverOut : function(event)
	    	{
	    		var mainAnchor = jQuery(event.target);
	        	var menu = mainAnchor.next('ul.dropdown');
	
	        	RMHC.dropdown.setTimerToHideMenu(menu);
	    	},
	
	    	menuHover : function()
	    	{
	    		RMHC.dropdown.clearTimer(jQuery(this));
	    	},
	
	    	menuHoverOut : function(event)
	    	{
	    		var ele = jQuery(event.target);
	
	    		if (event.target.tagName.toLowerCase() != 'ul' || !ele.hasClass('dropdown'))
	    			return;
	
	    		RMHC.dropdown.setTimerToHideMenu(ele);
	    	}
	    },
	
	    stories : {
	        init : function() {
	            var div = jQuery('div.stories');
	            jQuery('ul.nav li a', div).click(function() {
	                jQuery('ul.nav li a', div).removeClass('active');
	                jQuery('ul.feature-stories, ul.personal-stories', div).hide();
	                var css_class = jQuery(this).attr('class');
	                jQuery('ul.' + css_class + '-stories').show();
	                jQuery(this).addClass('active');
	                return false;
	            });
	        }
	    },
	
	    list_to_blinds : function(list) {
	        if (!list) {
	            return;
	        }
	
	        list.find('li.blind').not('li.blind-active').find('.blind-content').hide();
	
	        list.find('li.blind .blind-content li').each(function() {
	            jQuery('p:first', this).addClass('first');
	        });
	
	        list.find('li.blind').each(function() {
	            var id = jQuery('a[name]', this).attr('name');
	            if (!id) {
	                id = 'top';
	            }
	            jQuery('h3', this).wrapInner('<a href="#' + id + '"></a>');
	        });
	
	        list.find('li.blind h3 a').click(function() {
	            var was_open = false;
	
	            if ($(this).parents('li.blind').hasClass('blind-active')) {
	                was_open = true;
	            }
	
	            if (!was_open) {
	                $(this).parents('li.blind').addClass('blind-active');
	                $(this).parent().siblings('.blind-content').slideDown(200);
	            }
	            else {
	                $(this).parents('li.blind').removeClass('blind-active');
	                $(this).parent().siblings('.blind-content').slideUp(200);
	            }
	
	            return false;
	        });
	    },
		
		click_tracker: function() {
			$('a[@href^=assets/]').click(function() {
				var href = $.trim(this.href);
				var pos = href.lastIndexOf('/');
				
				if (pos < 0) {
					return;
				}
				
				var fileName = href.substr(pos + 1);
				
				pos = fileName.lastIndexOf('.');
				var fileType = (pos >= 0) ? fileName.substr(pos + 1).toLowerCase() : 'unknown';
	
				var trackingUrl = "/files/" + fileType + "/" + fileName;
				pageTracker._trackPageview(trackingUrl); 
			});
			
			$('a[href^=http://],a[href^=https://]').click(function() {
				var httpRegex = /^https?:\/\//;
				var href = $.trim(this.href).toLowerCase().replace(httpRegex, '');
				
				//don't track click to rmhc.org or donate.rmhc.org
				if (href.search(/donate.rmhc.org/) == 0 ||
					href.search(/(www\.)?rmhc.org/) == 0)
					return;
				
				var trackingUrl = '/external-link/' + href;
				pageTracker._trackPageview(trackingUrl); 
			});
		}
	};
	
	$(document).ready(RMHC.init);
	
})(jQuery);
