var OnlyGreen = function() {
	var youtube_videos = new Array();
	
    function init() {
        $(document.body).addClass('js');
        
        OnlyGreen.attachModalLinks();
        OnlyGreen.attachAutocomplete();
        OnlyGreen.attachLocalScroll();
        OnlyGreen.attachSlider();
        OnlyGreen.attachPngFix();
        OnlyGreen.attachSifr();
		OnlyGreen.attachVideoPreviewSendToFriend();
		OnlyGreen.attachYouTubeDeepLinks();
		OnlyGreen.attachYouTubePlay();
		OnlyGreen.attachMultipleSelect();
		OnlyGreen.attachYouTubePause();
		OnlyGreen.attachMaxLengthWarning();
		OnlyGreen.attachTracking();
    }
    
    function attachSifr() {
        $.sifr({
            build: 436,
            version: 3,
            path: '/static/sifr/',
            save: true
        });
        
        $('h2').sifr({
            font: 'GillSansStd',
            offsetTop: 3,
            fontSize: '23',
            tuneWidth: '10',
            debug: false
        });
    }
    
    function attachPngFix() {
        if (typeof(jQuery.fn.pngFix) == 'function') {
            $(document).pngFix();
        }
    }
    
    function attachModalLinks() {
        $('#modal-overlay-ajax').jqm({
            ajax: '@href',
            trigger: 'a.ajax-modal',
            onLoad: function(hash) {        	
                OnlyGreen.rebindModalHandlers('#modal-overlay-ajax');
				OnlyGreen.attachSifr();
				OnlyGreen.attachTracking();

				if (hash.t.toString().indexOf('#') != -1) {
					var urlCalled = hash.t.toString();
					var anchorToLoad = urlCalled.substring(
								urlCalled.indexOf('#'), 
								urlCalled.length
					);
					$('.modal-scroll').scrollTo(anchorToLoad, 800);
				}
            }
        });
    }
    
    function rebindModalHandlers(container) {
    	$(container + ' .jqmClose').click(function() {
        	$(container).jqmHide();
            return false;
        });
        
        $(container + ' form').ajaxify({
            complete: function() {
                OnlyGreen.rebindModalHandlers(container);
                OnlyGreen.attachSifr();
                OnlyGreen.attachTracking();
            }
        });
		$(container + ' form').attr('target', '#modal-overlay-ajax');
    }
    
    function attachAutocomplete() {
        var names = '';
        if (typeof(AUDIO_SUPPORTED_NAMES) != 'undefined') {
            names = AUDIO_SUPPORTED_NAMES.split(' ');
        }
        if (typeof(DEFAULT_OPTION) != 'undefined') {
	        $('.autocomplete-name').autocomplete(names, {
	        	appendOption: DEFAULT_OPTION
	        });
        }
    }
    
    function attachLocalScroll() {
        $('.pagination-container, .list-sub-nav').localScroll({
            target: '.pagination-container',
            queue: true,
            hash: true,
            duration: 1000,
            axis: 'x,y'
        });
    }
    
    function attachSlider() {
        $('form#form-policy-matchmaker ul li .question-answers ul').slider({
            range: 'min',
            animate: 150,
            value: 5,
            min: 0,
            max: 10,
            step: 0.1
        });
        
        $('form#form-policy-matchmaker').submit(function() {
            return OnlyGreen.submitSliderForm();
        });
    }
    
    function submitSliderForm() {
        $('form#form-policy-matchmaker ul li ul').each(function() {
            var selectedValue = Math.round($(this).slider('value'));
            
            // remove previously checked values
            $(this).find('input:checked').each(function() {
                $(this).attr('checked', '');
            });
            
            // check the relevant checkbox based on the slider position
            $(this).find('input').eq(selectedValue)
            				.attr('checked', 'checked');
        });
        
        return true;
    }
    
    function attachVideoPreviewSendToFriend(action) {
		$('#video-preview-modal').jqm({
			onHide: function(modal) {
				// We need to override the close method to remove the flash 
				// video when the overlay is closed to prevent it playing
				// in the background
				$('#video-preview').html('');
				modal.w.hide();
				modal.o.remove();
			}
		});    	
    	
		$('#encourage-send-to-a-friend, #encourage-preview').unbind('click');
		$('#encourage-send-to-a-friend, #encourage-preview')
												.click(function(event) {
			event.preventDefault();
			
			// Pull the hash link off the URL if present to prevent silly 
			// browsers passing this over in the request
			var formAction = $(this).parents('form').attr('action')
															.toString();
			formAction = formAction.substring(0, formAction.indexOf('#'));	
			
			formData = $(this).parents('form').serialize();
			if (event.target.id == 'encourage-send-to-a-friend') {
				formData += '&publish=1';
			} else {
				formData += '&preview=1';
			}
			
			$.ajax({
				type: 'POST',
				url: formAction,
				data: formData,
				success: function(response) {
					if (response.toString()
						.substring(0, 13) == '<!-- form -->') {
						// Errors occurred with form, so replace current 
						// form with HTML including error messaging
						$('#form-encourage').html(response.toString());

						OnlyGreen.init();						
					} else if (response.toString()
								.substring(0, 14) == '<!-- video -->') {
						// Form was submitted successfully and video embed 
						// HTML was returned
						$('#video-preview').html(response.toString());
						$('#video-preview-modal').jqmShow();
					} else if (response.toString().substring(0, 23) 
								== '<!-- send to friend -->'){
						// Form was submitted successfully and send to a 
						// friend form HTML was returned						
						$('#modal-overlay-ajax').jqm({
							ajax: false,
				            onShow: function(hash) {        	
        						hash.w.show();
        		
				                OnlyGreen.rebindModalHandlers(
				                			'#modal-overlay-ajax'
				                );
								OnlyGreen.attachSifr(); 
        					}								
						});
						$('#modal-overlay-ajax').html(response.toString());
						$('#modal-overlay-ajax').jqmShow();
												
						// Add video GUID to video URL
						FACEBOOK_FRIENDS_WALL_MESSAGE = 
							FACEBOOK_FRIENDS_WALL_MESSAGE.replace(
											'__guid__', 
											FACEBOOK_ARGS
							);
												
						OnlyGreen.init();
					}
				}
			});			
		});   	
    }
	
	function attachYouTubeDeepLinks() {
		var hash = window.location.hash.toString()
		if (hash.length > 0) {
			var videoId = hash.substring(1);
			$(window).scrollTo(videoId);
			playYouTubeVideo(videoId);
		}
		
		$('.list-sub-nav a').click(function() {			
			var href = $(this).attr('href').toString()
			var hash = href.substring(href.indexOf('#')+1);
						
			if (hash.length > 0) {				
				deactivateVideoLink(hash);
				playYouTubeVideo(hash);
			}
		});
	}
	
	function attachYouTubePlay() {	
		$('a.youtubeaction').click(function(event) {
			if ($(this).attr('rel') == 'next') {
				var youTubePlayerId = $(this).parents('li')
												.next('li').attr('id');
			} else if ($(this).attr('rel') == 'prev') {
				var youTubePlayerId = $(this).parents('li')
												.prev('li').attr('id');				
			}
			
			deactivateVideoLink(youTubePlayerId);
			playYouTubeVideo(youTubePlayerId);
		});		
	}
	
	function attachYouTubePause(){
		$('.policy-links li a.youtubeaction').click(function(event) {
			pauseAllVideos();
		});
	}
	
	function pauseAllVideos(currentVideo) {
		$('.player object, .player embed').map(function(index, element) {			
			var elementId = $(element).attr('id');
			if (elementId != currentVideo) {
				if (document.getElementById(elementId) && 
							document.getElementById(elementId).pauseVideo) {
					document.getElementById(elementId).pauseVideo();
				}
			}
		});	
	}
	
	function playYouTubeVideo(videoId) {
		var playerId = videoId + '-container';

		pauseAllVideos(videoId);
		updateOgData(videoId);
		
		if (typeof(videos) != 'undefined' && 
			typeof(videos[videoId]) != 'undefined') {	
			swfobject.embedSWF(
					videos[videoId].video + '&autoplay=1&rel=0', 
					playerId, 
					'488', 
					'300', 
					'8.0.0', 
					false, 
					flashvars, 
					params, 
					attributes
			);
		}
	}
	
	function updateOgData(videoId) {
		if (typeof(videos) != 'undefined' && 
			typeof(videos[videoId]) != 'undefined') {
			$('#og-title').attr('content', videos[videoId].title);
		}
	}
	
	function deactivateVideoLink(videoId) {
		// Remove active link class from all sub-links in navigation
		$('a[href*="/policies/"]').removeClass('active');
		$('ul.list-sub-nav li').removeClass('active');
		
		if (videoId != '') {
			// Add active class to currently playing video link
			$('a[href*="/policies/#' + videoId + '"]').addClass('active');
			$('a[href*="/policies/#' + videoId + '"]')
										.parent().addClass('active');
		}
	}
	
	function attachMultipleSelect() {
		$('#encourage-concerns input').click(function(event) {
			// Grabs the ID of the none concern hidden field which 
			// is passed through from Django
			var noneConcern = $('#id_none_concern').attr('value');
			
			// If 'none concern' field is checked, uncheck it if another
			// field has been clicked			
			if ($($(this).parents('#encourage-concerns')
					.find('input')[noneConcern]).attr('checked') 
					&& $(this).attr('value') != noneConcern) {
				$($(this).parents('#encourage-concerns')
						.find('input')[noneConcern]).attr('checked', false);
			}
			
			// If 'none concern' field is clicked, loop through all other
			// checkboxes and uncheck
			if ($(this).attr('value') == noneConcern) {
				var turnOff = true;
				if (!$(this).attr('checked')) {
					turnOff = false;
				}
				
				$(this).parents('#encourage-concerns')
					.find('input:checked').attr('checked', false);
				
				// If 'none concern' was on and clicked - turn it off
				if (turnOff) {
					$(this).attr('checked', true);
				}
			}
			
			// Do not allow more than two checkboxes to be checked
			if ($(this).parents('#encourage-concerns')
						.find('input:checked').length > 2) {
				event.preventDefault();
			}
		});
	}
	
	function attachMaxLengthWarning() {
		$('.sms-name').live('keyup', function() {			
			if ($(this).attr('value').length >= $(this).attr('maxlength')) {
				var errorMessage = MAX_LENGTH_MESSAGE.replace('%d', 
												$(this).attr('maxlength'));
				
				if ($('#max-char-error').length < 1) {
					$(this).parents('li').prepend('<ul class="errorlist" ' +
							' id="max-char-error"><li>' + errorMessage + 
							'</li></ul>');
				}
			} else {
				$('#max-char-error').remove();
			}
		});
	}
	
	function attachTracking() {
		$('.track, .track-outbound').unbind('.tracking');
		
		$('a.track').bind('click.tracking', function() {
			track('page', {
				url: $(this).attr('href')
			});
		});
		
		$('form.track').bind('submit.tracking', function() {
			track('event', {
				url: $(this).attr('action'),
				action: 'form-submit',
				opt_label: $(this).children('button').attr('name')
			});
		});
		
		$('a.track-outbound').bind('click.tracking', function() {
			track('event', {
				url: $(this).attr('href'),
				action: 'outbound-link'
			});
		});
	}
	
	function track(type, trackingData) {
		if (typeof(pageTracker) == 'undefined' ||
				typeof(pageTracker._trackPageview) == 'undefined' ||
				typeof(pageTracker._trackEvent) == 'undefined') {
			return false;
		}
		
		switch(type) {
			case 'page':
				if (typeof(trackingData.url) != 'undefined') {
					pageTracker._trackPageview(trackingData.url);
				}
				break;
			case 'event':
				if (typeof(trackingData.url) != 'undefined' &&
						typeof(trackingData.action) != 'undefined') {
					pageTracker._trackEvent(
						trackingData.action,
						trackingData.url,
						(trackingData.opt_label ? 
									trackingData.opt_label : null),
						(trackingData.opt_value ? 
									trackingData.opt_value : null)
					);			
				}
				break;
		}
	}
		
    return {
        init: init,
        attachModalLinks: attachModalLinks,
        rebindModalHandlers: rebindModalHandlers,
        attachAutocomplete: attachAutocomplete,
        attachLocalScroll: attachLocalScroll,
        attachSlider: attachSlider,
        submitSliderForm: submitSliderForm,
        attachPngFix: attachPngFix,
        attachSifr: attachSifr,
		attachVideoPreviewSendToFriend: attachVideoPreviewSendToFriend,
		attachYouTubeDeepLinks: attachYouTubeDeepLinks,
		attachYouTubePlay: attachYouTubePlay,
		deactivateVideoLink: deactivateVideoLink,
		attachMultipleSelect: attachMultipleSelect,
		playYouTubeVideo: playYouTubeVideo,
		updateOgData: updateOgData,
		attachYouTubePause: attachYouTubePause,
		attachMaxLengthWarning: attachMaxLengthWarning,
		attachTracking: attachTracking,
		track: track
    };
}();

$(document).ready(function(){
    OnlyGreen.init();
});
