var rsUI = {
	/*
	 * Simulate first-child, last-child on <li> elements
	 */
	domLIFix:function(){
              if($('ul')){
		$('ul').find('>li:last').addClass('last-child');
		$('ul').find('>li:first').addClass('first-child');
              }
	},

	/*
	 * Definition and function to create our navigation dropdown menus
	 * @param caller DOM calling object
	 * @returns object {menuObject: jQuery(object), controlElements: Array(jQuery(object),...)}
	 */
	
	menuDefinitions:{
		
		
		_audioMenu:function(caller){
			var d = $('<div>').addClass('generated-audio');
			var c = $(caller);
			var p = c.offset();
			var w = c.width();			
			var html = '<strong>Reinforce your learning anywhere — at home, in the car, or on the go.</strong>';
			html += '<ul><li>Download the sound files to your MP3 player or computer.</li>';
			html += '<li>Access your lessons whenever and wherever you want.</li>';
			html += '<li>Hear and repeat questions and answers to use in conversations.</li></ul>';
			
			c.css({cursor:'help'});
			d.append($('<div>').addClass('top'));
			d.append($('<div>').addClass('mid').html(html));
			d.append($('<div>').addClass('bot'));

			d.css({display:'block',visibility:'hidden',top:p.top-20,left:p.left+w});
			
			$('body').append(d); // Add to top-level of DOM	
			
			d.css({visibility:'visible',display:'none'});
			
			return {menuObject:d, controlElements:[d,c]}
			
		},
		
		/*
		 * For internal sub menus
		 */
	   _subMenu:function(caller){

			var m = $(this).next('ul.sub-menu').get(0);
			var c = $(m).clone(true);
			var cc = $(m).clone(true);
                        if(this.id == "Languages")
  			  var d = $('<div onmouseover="rsUI.hide_dropdown(\'none\');" onmouseout="rsUI.hide_dropdown(\'block\');">').addClass('generated-sub-menu');
                        else
                          var d = $('<div>').addClass('generated-sub-menu');
			var p = $(caller).offset(); // Get X/Y of our calling object
			
			/* 
			 * This needs to size dynamically so we need a width of the elements
			 */
			var w = c.virtualWidth();
		        w = w < 200 ? 200 : w;
			//w+=20; // Add 20 to width for padding
			var h4 = $('<h4>').append($(caller).clone());
			d.append($('<div>').addClass('generated-sub-menu-header').append(h4)); 
			d.append(
				$('<div>').addClass('generated-sub-menu-content').append(
					$('<div>').addClass('sub-menu-content').append(c)
				)
			);  
			d.css({display:'none',top:p.top-8,left:p.left-2,width:w,height:1}); // Position according to design
			$('body').append(d); // Add to top-level of DOM	

			return {menuObject:d, controlElements:[h4,c]}	

		},

		/*
		 * For top support list
		 */
		_supportMenu:function(caller){
			var m = $(this).next('ul').get(0);
			var c = $(m).clone(true);
			var d = $('<div>').addClass('generated-support-list');
			var p = $(caller).offset(); // Get X/Y of our calling object

			var h4 = $('<h4>').text($(caller).text());
			d.append($('<div>').addClass('generated-support-list-header').append(h4));
			d.append($('<div>').addClass('generated-support-list-content').append(c));  
			d.css({display:'none',top:p.top-5,left:p.left-7});// Position according to design
			$('body').append(d); // Add to top-level of DOM	

			return {menuObject:d, controlElements:[h4,c]}			
		},
		
		/*
		 * For top country list
		 */
		_countryMenu:function(caller){
			var m = $(this).parent().parent('ul').get(0);
			var c = $(m).clone(true);
			var d = $('<div>').addClass('generated-country-list');
			var p = $(caller).offset();		
			
			c.find('li').each(function(){
				if($(this).find('a').text() == $(caller).text()){
					$(this).remove();
				}
			});	
			
			var h4 = $('<h4>').text($(caller).text());
			d.append($('<div>').addClass('generated-country-list-header').append(h4));
			d.append($('<div>').addClass('generated-country-list-content').append(c));
			d.css({display:'none',top:p.top-5,left:p.left-7}); // Position according to design
			$('body').append(d); // Add to top-level of DOM
			
			return {menuObject:d, controlElements:[h4,c]};			
		}	
		
	},

        hide_dropdown:function(style_property){
          if(navigator.userAgent.indexOf('MSIE 6')!= -1 && document.getElementById('osub-select')){
            document.getElementById('osub-select').style.display = style_property;
          }
        },
         
       initCountryDropdown:function(){
	 if($('.country-select li.active a')){
           $('.country-select li.active a').enableMenuOverlay(rsUI.menuDefinitions._countryMenu);
         }
	},
	
	initSupportDropdown:function(){
          if($('.support-select>a')){
	    $('.support-select>a').enableMenuOverlay(rsUI.menuDefinitions._supportMenu);
          }
	},
	
	initLangDropdown:function(){
	  if($('#lang-dropdown span.title a')){	
            $('#lang-dropdown span.title a').click(function(e){
	    e.preventDefault();
			var s = $('#lang-selections');
			if(s.is(':visible')){
				$(this).removeClass('active');
				s.hide(50,function(){ $('body').unbind('click',rsUI._closeLangBox)});
			}else{
				$(this).addClass('active');
				$('body').bind('click',rsUI._closeLangBox);
				s.show(50,function(){
					if(s.find('a.close-selection').length == 0){
						var a = $('<a>').addClass('close-selection').click(function(){s.hide()});
						s.append(a);
					}
				});
			}
			return false;			
		});
	  }	
	},
	
	_closeLangBox:function(e){
		var s = $('#lang-selections');
		if(s.is(':visible')){
			s.hide(50,function(){ $('body').unbind('click',rsUI._closeLangBox)});
		}		
	},
	
	/*
	 * Create dynamic menus
	 */   
   initSubMenus:function(){
     if($('#subnav>ul>li')){   
       $('#subnav>ul>li').each(function(){
         var li = $(this);
	 if(li.find('ul.sub-menu').length > 0){
	   li.find('a:first').enableMenuOverlay(rsUI.menuDefinitions._subMenu);
	 }	
       });
     }
   },

	/*
	 * Applies mouseover and mouseout to our menu calling element
	 * @param menuCreateCallback function
	 */
	_applyMenuControls:function(menuCreateCallback){
		$(this).each(function(){
			$(this).bind('mouseover', function(e){
				var caller = e.target;					
				clearTimeout(caller.timer);
				if(!caller.menuActive){
					rsUI._createMenu(caller, menuCreateCallback);
				}
			}).bind('mouseout',function(e){
				var caller = e.target;
				caller.menuActive = false;				
				caller.timer = setTimeout(function(){
					if(caller.menuActive == false){
						$(caller.menu).slideUp(10,function(){try{d.remove()}catch(e){}});
					}
				},50);
			
			});
		});		
		
	},
	/*
	 * Create menu dropdown
	 * @param caller DOM node (<a>)
	 * @param menu DOM node (<ul>)
	 */
   _createMenu:function(caller, menuDefCallback){
   
		if(!caller.menuActive){
			
			$('.visible-generated-menu').remove();
		
			/*
			 * Generate the menu in memory and append necessary elements
			 * callback should return {menuObject:(object), controlElements:[array]}
			 * Where controlElements are the elements in the menu that  
			 * have the mouseover and mouseout events to control the display
			 */
			var o = menuDefCallback.call(caller, caller);
			
			/*
			 * Assign our menu to the caller for future use and create property
			 * menuActive
			 */
			caller.menu = o.menuObject.get(0);
			caller.menuActive = true;			
		
			/*
			 * Attach mouse events to the <h4> and <ul> tag
			 * We don't attach to the container itself because the design of
			 * the menu overlays the regular navigation
			 */				
			$(o.controlElements).each(function(){
				$(this).bind('mouseover',function(e){
					caller.menuActive = true;
					clearTimeout(caller.timer); // Clear timer if set
				}).bind('mouseout',function(e){
					caller.menuActive = false;
					/*
					 * The timer gives the user an interval to navigate from
					 * the original item to the menu.  If we don't do this, the menu
					 * would hide immedately after we mouseout of the <h4> tag
					 */
					caller.timer = setTimeout(function(){
						if(caller.menuActive == false){
							$(caller.menu).slideUp(50,function(){o.menuObject.remove()});
						}
					},50);
				});
			});
		
			/*
			 * Show the menu
			 */
			o.menuObject.addClass('visible-generated-menu');
			o.menuObject.slideDown('fast',function(){caller.menuActive = true;});     		
			
		}
      
   },
	signupInit:function(){
	if($('#signup-email, #newsletter-email')){	
         $('#signup-email, #newsletter-email').focus(function(){
			var me = $(this);
			me.val(me.val() == 'your e-mail address here' ? '' : me.val());
		}).
		blur(function(){
			var me = $(this);
			me.val(me.val() == '' ? 'your e-mail address here' : me.val());			
		});		
         }
	},

        setupAjaxFormHooks:function(){
                var timer;
                // naive
                var animate = function(){
                    var txt = $('#processing');
                    var text = txt.text();
                    var idx = text.indexOf('.');
                    if(idx != -1){
                      if(text.substr(idx).length == 3){
                        txt.text(text.substr(0,idx));
                      }
                      else{
                        txt.text(text + '.');
                      }
                    }
                    else{
                      txt.text(text + '.');
                    }
                    
                };
                var kill_animation = function(){
                    window.clearInterval(timer);
                };
                if($('#email-form')){
                $('#email-form').submit(function(e){
                        e.preventDefault();
                        var email = this['form[email]'].value;
                        var id = this['form[identifier]'].value;
                        var post_str = 'form[email]=' + email + '&form[identifier]=' + id;
                        jQuery.ajax({
                               type: 'POST',
                               url: this.action,
                               data: post_str,
                               success: function(resp, status){
                                 kill_animation();
                                 if(resp.indexOf('errorExplanation') != -1){
                                   $('#processing').addClass('hide');
                                   $('#error-email').removeClass('hide');
                                   window.setTimeout(function() {$('#error-email').addClass('hide'); $('#email-form').removeClass('hide');}, 3000);
                                 }
                                 else{
                                   $('#processing').addClass('hide');
                                   $('#thank-you').removeClass('hide');
                                 }
                                 return false;
                               },
                               error: function(resp, status, error){
                                 kill_animation();
                                 $('#processing').addClass('hide');
                                 $('#error').removeClass('hide');
                                 window.setTimeout(function() {$('#error').addClass('hide'); $('#email-form').removeClass('hide');}, 2000);
                                 return false;
                               }
                        });
                 $('#email-form').addClass('hide');
                 $('#processing').removeClass('hide');
                 timer = window.setInterval(animate, 200);
                 return false;
                });
             }
        },

	subnavActivate:function(){
        if($('#subnav>ul>li>a.active')){
		var a = $('#subnav>ul>li>a.active');
		a.css({position:'relative',zIndex:3})
		if(a.length >0){
			var d = $('<div>').css({
				position:'absolute',
				background:'transparent url(/us_assets/redesign/images/inavbgright.gif) no-repeat top right',
				height:'25px',
				top:a.get(0).offsetTop -4,
				left:a.get(0).offsetLeft - 7,
				zIndex:2,
				width:a.outerWidth() - 10
			});
			var dd = $('<div>').css({
				font:'normal 13px/25px Arial,sans-serif',
				background:'transparent url(/us_assets/redesign/images/inavbgleft.gif) no-repeat top left',
				height:'25px', 
				color:'#000',
				paddingLeft:10,
                                width:a.outerWidth() - 20
			});
			
			$(a).before(d.append(dd));			
		}
           }
	} ,
	tertiaryNavActivate:function(){
          if($('.internal-nav ul li')){
                $('.internal-nav ul li').hover(function(){ $(this).addClass('hover')},function(){$(this).removeClass('hover')});}
if($('.internal-nav-condensed ul li')){
                $('.internal-nav-condensed ul li').hover(function(){ $(this).addClass('hover')},function(){$(this).removeClass('hover')});
}
	},
	offeringActivate:function(){
	if($('#product-offering>ul>li>a')){	
		$('#product-offering>ul>li>a').click(function(e){
			e.preventDefault();
			var a = $(this);
			var h = a.attr('href').substr(1);
			$('#product-offering>ul>li>a').removeClass('active');
			$('.offering-content').each(function(){
				if($(this).is(':visible')){
					$(this).fadeOut(function(){
						$('#'+h).fadeIn();
					});					
				}
			});						
			a.addClass('active');
		});		
         }
	},
	audioMenus:function(){
        if($('.audio-companion')){
      $('.audio-companion').each(function(){
			var tag = $(this);
			tag.enableMenuOverlay(rsUI.menuDefinitions._audioMenu);		
		});		}
	},
	loadVideoMoment:function(videoUrl, caller){
		var player = $('#moment-flash-video').get(0);		
		player.loadVideoBySrc(videoUrl);		
		
		$('.video-selections>ul>li>a').removeClass('active');
		$(caller).addClass('active');
		
	},
//Not the best code but works for now
        replaceMomentVideo:function(params, flashvars, caller, current){
          parameters = {
            allowFullScreen: "true",
            bgcolor: params['bgcolor'],
            wmode: params['wmode'],
            base: params['base'],
            allowscriptaccess: 'always'
          };

         width = params['width'];
         height = params['height'];
         min_version = params['min_version'];
         player = params['player'];
         express_install = params['express_install'];

         attributes = {
           id: 'moment-flash-video'
         };

        vars = {
          video: flashvars['video'],
          dataSource: flashvars['dataSource'],
          preview: flashvars['preview']
        };

        swfobject.embedSWF(player, caller, width, height, min_version, express_install, vars, parameters, attributes);
        $('.video-selections>ul>li>a').removeClass('active');
        $(current).addClass('active');

        },
        setDefaultsAndReplaceMomentVideo:function(video_url, preview_url,data_url, caller, current){
          params = {
            width: '230',
            height: '152',
            min_version: '9.0.28',
            player: '/us_assets/redesign/flash/MiniVideo.swf',
            express_install: '/us_assets/redesign/flash/expressInstall.swf',
            bgcolor: 'fbf8e5',
            wmode: 'transparent',
            base: '/us_assets/redesign/flash/'
          };

          vars = {
            video: video_url,
            dataSource: data_url,
            preview: preview_url
          };
          rsUI.replaceMomentVideo(params, vars, caller, current);
        },
	loadVideoLightbox:function(flvFile){
		
		var iframeHeight = 601;
		var iframeWidth = 708;
		
		if(typeof flvFile != 'undefined'){
			iframeHeight = 500;
	   	iframeWidth = 708;
		}
		
	   $(document.documentElement).css('overflow','hidden');
	   
	   var st = document.documentElement.scrollTop||document.body.scrollTop;
	   var wh = $(window).height();
	   var ww = $(window).width();
	
		/*if(wh < 630){
			if(!confirm("The video you are about to play is larger than your viewable area and controls may not be visible.\n\nWhen the video has completed, you must click your browser's reload or refresh button to close the video.")){
				return;
			}			
		}*/
		
           var d = $('<div>').addClass('video-lightbox').css({zIndex:8000,background:'#000',opacity:0.85,position:'absolute',top:0,left:0,width:ww,height:'2000px'});
           var ifr = $('<iframe>').addClass('video-iframe').attr({scrolling:'no',border:'0','frameBorder':'none',src:'/us_assets/redesign/flash/personal_demo/lightbox.html'}).css({zIndex:8001,position:'absolute',border:0,width:796,height:565,top:(wh/2-275)+st,left:(ww/2-355)});

	   $('body').append(d);	   
	   $('body').append(ifr);
	   
	   $(window).bind('resize', rsUI.redrawLightbox);
	},
	
	redrawLightbox:function(){
	   if($('.video-lightbox').length > 0){
	      setTimeout(function(){
      	   var st = document.documentElement.scrollTop||document.body.scrollTop;
      	   var wh = $(window).height();
      	   var ww = $(window).width();
      	   $('.video-lightbox').css({top:0,left:0,width:ww,height:wh+st});   
      	   $('.video-iframe').css({top:(wh/2-300)+st,left:(ww/2-355)});
      	},10);
	   }
	},
	
	resizeLightbox:function(width,height,callback){
	   if($('.video-lightbox').length > 0){
	      setTimeout(function(){
      	   var st = document.documentElement.scrollTop||document.body.scrollTop;
      	   var wh = $(window).height();
      	   var ww = $(window).width();
      	   $('.video-iframe').animate({top:(wh/2-height/2)+st,width:width,height:height,left:(ww/2-width/2)},function(){
      	      callback.call(this);      	      
      	   });
      	},10);
	   }
	},
	
	closeVideoLightbox:function(){
	 	$('.video-lightbox, .video-iframe').remove();
	 	$(document.documentElement).css('overflowY','auto');
	 	$(window).unbind('resize', rsUI.redrawLightbox);
	},
	
	curLangImage:0,
	
	rotateLangs:function(){
		if($('#rotate-langs>li')){
		if($('#rotate-langs>li').length == 0) return;
		
		this.langImages = $('#rotate-langs>li');
		var me = this;
		
		setInterval(function(){
			me.langImageLoop();
		},9000);
           }
	},
	
	langImageLoop:function(){
		var me = this;
		me.curLangImage++;
		if(me.curLangImage > me.langImages.length -1) me.curLangImage = 0;
		
		$('#rotate-langs>li:visible').fadeOut(function(){
			$(me.langImages[me.curLangImage]).fadeIn(function(){
			
			});
		});		
	}
}

var loadVideoLightbox = rsUI.loadVideoLightbox; // For home flash

/*
 * Extend jQuery for _applyMenuControls
 */
$.fn.enableMenuOverlay = rsUI._applyMenuControls;

$.fn.virtualWidth = function(){
	var cc = $(this).clone(true);
	cc.css({width:'auto',cssFloat:'left',visibility:'hidden',display:'block'});
	$('body').append(cc);
	var w = cc.outerWidth();
	cc.remove();
	return w;	
}


/*
 * Initialize the page(s)
 */ 

$(function(){ 
	rsUI.domLIFix();
	rsUI.initCountryDropdown();
	rsUI.initSubMenus(); 
	rsUI.initLangDropdown();
	rsUI.initSupportDropdown();
	rsUI.signupInit();
	rsUI.subnavActivate();
        rsUI.setupAjaxFormHooks();
	rsUI.tertiaryNavActivate();
	rsUI.offeringActivate();
	rsUI.rotateLangs();
	rsUI.audioMenus();
});
