// This file is automatically included by javascript_include_tag :defaults
/* -----------------------------------*/
/* -----------------------------------*/



document.observe("dom:loaded", function() {
	init();
});


function init() {
	replaceZoneHeader();
	//replace_comment_response_form();
	replace_overview_comment();
	//Any functions to be called on pageload should be called here, ala "myFunction(foo);"
	initGallery();
	initForms();
	//initPopups();
	initHome();
	initWatch();
	initLoginForm();
	loginFieldsHelper();
	initComments(); 
	preloadimages();
	initDownSliders();
}

// Add labels helper to login form
function loginFieldsHelper() {
	if ($('utility_login')) {
			$('login').labelActsAsHint("Username or email address");
			$('password').labelActsAsHint("Password");
	}
}

function initCasualUserFields() {
	if($('post_comment_extra')) {
		if ($('post_comment_username','post_comment_useremail')) {
			$('post_comment_username').labelActsAsHint('Name (required)');
			$('post_comment_useremail').labelActsAsHint('Email address (required)');
		}
	}
}

/* Title comment related functions */

var showTabNonRegistered = function showTabNonRegistered() {
	// update button image
	$('post_submit_comment').src = "/resources/images/ui/buttons/button-post-comment-off.gif";
	$('post_comment_username').labelActsAsHint('Name (required)');
	$('post_comment_useremail').labelActsAsHint('Email address (required)');
	$('post_comment_new_user_form').show(); 
	$('post_comment_existing_user_form').hide(); 
	if($('recaptcha-credit')) {
		$('recaptcha-credit').style.display = 'inline';
	}
	initCasualUserFields();
}

var showTabRegistered = function showTabRegistered() {	
	// update button image
	$('post_submit_comment').src = "/resources/images/ui/buttons/button-post-login-off.gif";
	$('login').labelActsAsHint('Username or email address');
	$('password').labelActsAsHint(); 
	$('post_comment_existing_user_form').show(); 
	$('post_comment_new_user_form').hide();
	$('recaptcha-credit').hide();
}

function initLoginForm() {
	// Get form if it exists
	var login_form = null;
	if($('login-form')) {
		login_form = $('login-form');
	} else if($('title_comment')) {
		login_form = $('title_comment');
	} 
	// Add timed observer to clear labels when input fields auto completed.
	if(login_form != null) {
		new Form.Observer(login_form, 0.1, function(form, value) {
			var user_field = $('login');
			var pass_field = $('password');
			if(user_field && !user_field.value.empty()) {
				user_field.up('p').down('label').addClassName('hastext');
			}
			if(pass_field && !pass_field.value.empty()) {
				pass_field.up('p').down('label').addClassName('hastext');
			}
      	});
	}
}


// Watch > Title comments
function initComments() {
	if($$('.section_watch #title_comment #post_comment_extra')[0]) {
		if ($$('.section_watch .errorExplanation')[0]) { // if we have an error
			$('post_comment_extra').style.display = 'block'; // show the form
			if($('widget_title_commenting_tip')) {
				$('widget_title_commenting_tip').style.display = 'block'; // show information widget
			}
			$('Textarea').addClassName('active');
		} else {
			titleCommentReplyExpand(); // otherwise add textarea listener
		}
		// Initial Load
		if($('post_comment_user_status_a') && $('post_comment_user_status_a').checked) {
			showTabNonRegistered();
		} else if( $('post_comment_user_status_b') && $('post_comment_user_status_b').checked) {
			showTabRegistered();
		}
	
		// Remove opposite login form before submit to prevent validation breaking.
		$('title_comment').observe('submit',function(){
			if($('post_comment_user_status_a').checked) {
				$('post_comment_existing_user_form').remove();
			} else {
				$('post_comment_new_user_form').remove();
			}
		});
		
		// Comment subform listeners
		if($('post_comment_user_status_a') && $('post_comment_user_status_b')) {
			$('post_comment_user_status_a').observe('click', showTabNonRegistered);
			$('post_comment_user_status_b').observe('click', showTabRegistered);
		}
	}
}

function initHome() {
  if ($$('.section_home')[0]) { //Tabs for Recently Viewed and Most Viewed
    
    initHomepageSlider();
		
    Event.observe(window, 'load', function() {
      $('most_viewed').observe('click', function(ev) {
        $('most_viewed').addClassName('active');
        $('recently_added').removeClassName('active');
        $('panel_1').hide();
        $('panel_2').show();
        Event.stop(ev);
      });
      $('recently_added').observe('click', function(ev) {
         $('recently_added').addClassName('active');
         $('most_viewed').removeClassName('active');
         $('panel_2').hide();
         $('panel_1').show();
         Event.stop(ev);
       });
    });
  }
}

function initWatch() {
  if ($('widget_usertools_2')) { //Tabs for Favourite/Share/Email/Badge It
		
    Event.observe(window, 'load', function() {
      $('menu_favourite').observe('click', function(ev) {
        $('menu_favourite').addClassName('active');
        $('menu_share').removeClassName('active');
        $('menu_email').removeClassName('active');
				
				if ( $('menu_badgeit') )
				{				
       	 $('menu_badgeit').removeClassName('active');	// 'badge it' is a separate story
				}
					
        $('panel_1').show();
        $('panel_2').hide();
        $('panel_3').hide();
				
				if ( $('panel_4') )
				{			
       	 $('panel_4').hide();	// 'badge it' is a separate story	
				}				
		
        Event.stop(ev);
      });
      $('menu_share').observe('click', function(ev) {
        $('menu_favourite').removeClassName('active');
        $('menu_share').addClassName('active');				
        $('menu_email').removeClassName('active');
				
				if ( $('menu_badgeit') )
				{					
       	 $('menu_badgeit').removeClassName('active');	// 'badge it' is a separate story
				}				
						
        $('panel_1').hide();
        $('panel_2').show();
        $('panel_3').hide();

				if ( $('panel_4') )
				{			
       	 $('panel_4').hide();	// 'badge it' is a separate story		
				}		

        Event.stop(ev);
      });	
      $('menu_email').observe('click', function(ev) {
        $('menu_favourite').removeClassName('active');
        $('menu_share').removeClassName('active');				
        $('menu_email').addClassName('active');

				if ( $('menu_badgeit') )
				{			
       	 $('menu_badgeit').removeClassName('active');	// 'badge it' is a separate story		
				}		

        $('panel_1').hide();
        $('panel_2').hide();
        $('panel_3').show();

				if ( $('panel_4') )
				{				
       	 $('panel_4').hide();	// 'badge it' is a separate story		
				}
				
				$('emailfriend_email').onfocus = function() 
				{
  				if (this.value == 'Email address') this.clear();;
  			}
  			$('emailfriend_email').onblur = function() 
  			{
  				if (!this.present()) this.value= "Email address";
  			}
  			$('emailfriend_comments').onfocus = function() 
  			{
  				if (this.value == 'Enter your message here') this.clear();;
  			}
  			$('emailfriend_comments').onblur = function() 
  			{
  				if (!this.present()) this.value= "Enter your message here";
  			}
  			$('emailfriend_sender').onfocus = function() 
  			{
  				if (this.value == 'Your name') this.clear();;
  			}
  			$('emailfriend_sender').onblur = function() 
  			{
  				if (!this.present()) this.value= "Your name";
  			}
        
        Event.stop(ev);
      });				
			
			if ( $('menu_badgeit') )	// 'badge it' is a separate story
			{				
				$('menu_badgeit').observe('click', function(ev) {
					$('menu_favourite').removeClassName('active');
					$('menu_share').removeClassName('active');				
					$('menu_email').removeClassName('active');
					$('menu_badgeit').addClassName('active');				
					$('panel_1').hide();
					$('panel_2').hide();
					$('panel_3').hide();
					$('panel_4').show();				
					Event.stop(ev);
				});										
			}			
    });
  }
}

// A re-write of the Collections slider so that it is re-usable elsewhere.
// Also added the pagination functions.
function initHomepageSlider() {
	$$('.slider-panel').each(function(slider) {
		
		// display if js enabled
		if (slider.select('.slider-nav-panel')[0]) {
			slider.select('.slider-nav-panel')[0].style.display = 'block';
		}
		
		var sections = slider.select('.slider_section').length;
		//alert('sections='+sections);
		var current_section = 1;
		if (sections >1) {
				var $nextlink = slider.select('.slider-nav-panel li.next a');
				var $prevlink = slider.select('.slider-nav-panel li.previous a');
				// Update nav-panel links on first run
				if (current_section == sections) {
					$nextlink[0].hide();
				}
				if (current_section == 1) {
					$prevlink[0].hide();
				}
				
				// Next link
				$nextlink[0].observe('click', function(ev) {
					//alert(current_section);	
					if ( current_section != sections) {
						slidePanel(ev, 'next', slider, 'relative');
						current_section = current_section + 1;
						slider.select('.slider-nav-panel li.middle')[0].getElementsBySelector('a').invoke('removeClassName','active')[current_section -1].addClassName('active');
						//alert(current_section);	
						if ( current_section == sections) {
							this.hide();
						}
					}
					$prevlink[0].show();
					Event.stop(ev);
				});
				
				// Previous link
				$prevlink[0].observe('click', function(ev) {
					//alert(current_section);
					if ( current_section != 1) {
						slidePanel(ev, 'previous', slider, 'relative');
						current_section = current_section - 1;
						slider.select('.slider-nav-panel li.middle')[0].getElementsBySelector('a').invoke('removeClassName','active')[current_section -1].addClassName('active');
						//alert(current_section);	
						if ( current_section == 1) {
							this.hide();
						}
					} 
					$nextlink[0].show();
					Event.stop(ev);
				});
				
				// Jump links
				slider.select('.slider-nav-panel li.middle li a').each( function(link, index) {
					link.observe('click', function(ev) {
						current_section = (index + 1);
						//alert(current_section);
						slidePanel(ev, index, slider, 'absolute');
						slider.select('.slider-nav-panel li.middle li a').each(function(a) {
							a.removeClassName('active');
						});
						link.addClassName('active');
						// show/hide next & previous
						//alert('index='+index+' and sections='+sections-1);
						if (index == (sections-1)) {
							$nextlink[0].hide();
							$prevlink[0].show();
							//alert('at the end')
						} else if (index == 0) {
							$nextlink[0].show();
							$prevlink[0].hide();
						} else {
							$nextlink[0].show();
							$prevlink[0].show();
						}
						Event.stop(ev);
					});
				});
			
		} else {
			// hide the nav - this is not needed as the rails app hides the nav as well, but its here just in case.
			slider.select('.slider-nav-panel')[0].hide();
		}
	});
}

/* Slides the Homepage slider panels
	 Options include: 
			method = absolute|relative 
			slider = targetparentelement
			direction = next|previous|integer			
*/
function slidePanel(e, direction, slider, method) {
	if (direction=='next') {
		distance = '-554';
	} else if (direction=='previous') {
		distance = '554';
	} else {
		distance = (direction * -554)
	}
	//alert(distance);
	new Effect.Move(slider.select('.slider')[0], {
   	//x: distance, mode: method, transition: Effect.Transitions.fastsinoidal, duration: 1  });
	x: distance, mode: method, transition: Effect.Transitions.EaseFromTo, duration: 1 });
	
	Event.stop(e);
}

/*
- EaseFromTo (adapted from “Quart.EaseInOut”)

Based on Easing Equations v2.0
(c) 2003 Robert Penner, all rights reserved.
This work is subject to the terms in http://www.robertpenner.com/easing_terms_of_use.html
Adapted for Scriptaculous by Ken Snyder (kendsnyder ~at~ gmail ~dot~ com) June 2006
*/
Effect.Transitions.EaseFromTo = function(pos) {
	if ((pos/=0.5) < 1) return 0.5*Math.pow(pos,4);
	return -0.5 * ((pos-=2)*Math.pow(pos,3) - 2);
};


// Deprecated
/*
function initCollections() {
  var sections = $$('.slider_section').length;
  var current_section = 1;

  if($('collections_next')) {
      $('collections_next').observe('click', function(ev) {
        if ( current_section != sections) {
          new Effect.Move($$('.slider')[0], {
            x: -554, mode: 'relative', transition: Effect.Transitions.fastsinoidal, duration: 0.6
          });
          current_section = current_section + 1;
          $$('.middle')[0].getElementsBySelector('a').invoke('removeClassName','active')[current_section -1].addClassName('active');
        }
        Event.stop(ev);
      });
  }
  if($('collections_previous')) {
      $('collections_previous').observe('click', function(ev) {
        if ( current_section != 1) {
          new Effect.Move($$('.slider')[0], {
            x: 554, mode: 'relative', transition: Effect.Transitions.fastsinoidal, duration: 0.6
          });
          current_section = current_section - 1;
          $$('.middle')[0].getElementsBySelector('a').invoke('removeClassName','active')[current_section -1].addClassName('active');
        }
        Event.stop(ev);
      });
  }
}
*/

/* Deprecated */
Effect.Transitions.fastsinoidal = function(pos) {
  // pos = pos * 2;
  return ((-Math.cos(pos*Math.PI)) + 1) / 2;
}

//these methods are cache busters. We replace empty or sparsely populated
//sections of pages with the "proper" content
function replaceZoneHeader() {
	new Ajax.Request('/public/get_zone_header', {
		method: 'get',
		onSuccess: function(transport) {
			Element.replace('nav_supplimentary', transport.responseText);
			operaFix();
			// HE: Commented this out becuase it was initialising twice causing binding issues.
      initPopups();
		}
	});
}

function replace_comment_response_form() {
  if ($('widget_comments_postresponse') && $('sluggy')) {    
    new Ajax.Request('/public/get_comment_response/' + $('sluggy').innerHTML, {
      method: 'get',
      onSuccess: function(transport) {
        Element.replace('widget_comments_postresponse', transport.responseText);
        operaFix();
        css_imagereplace();
				initForms();
      }
    });
  }
    
}

function replace_overview_comment() {
  if ($('widget_discuss') && $('overview-slug')) {
    new Ajax.Request('/public/get_overview_comment/' + $('overview-slug').innerHTML, {
      method: 'get',
      onSuccess: function(transport) {
        Element.replace('widget_discuss', transport.responseText);
        operaFix();
        css_imagereplace();
      }
    });
  }
    
}

// Expand the reply textarea on click
function titleCommentReplyExpand(status) {
	if($$('.section_watch #title_comment #widget_reply textarea')[0] != null) {
		$$('.section_watch #title_comment #widget_reply textarea')[0].up(0).removeClassName('active'); // hide on load
		if (($$('.section_watch #title_comment #widget_reply textarea')[0].value != 'Your comment') && ($$('.section_watch #title_comment #widget_reply textarea')[0].value != '')) {
			$$('.section_watch #title_comment #widget_reply textarea')[0].up(0).addClassName('active');
			$('post_comment_extra').style.display = 'block'; // show the form
		} else {
			$$('.section_watch #title_comment #widget_reply textarea')[0].observe('focus', function() {
				$('post_comment_extra').style.display = 'block'; // show the form
				$('widget_title_commenting_tip').style.display = 'block'; // show widget
				
				// Clears default text in the textarea to the editor.
				if (this._cleared) return
				this.clear()
				this._cleared = true
				this.up(0).addClassName('active');
				// Clear form labels if needed
				initLoginForm();
			});
		}
	}
}

function mouseInZone(element, ev){
	a = $(element).viewportOffset();
	
	w = $(element).getWidth();
	h = $(element).getHeight();
	
	mouseX = ev.clientX;
	mouseY = ev.clientY;
	
	if(mouseX > a[0] && mouseY > a[1] && mouseX < (a[0] + w) && mouseY < (a[1] + h)){
		return true;
	} else {
		return false;
	}
}


function initPopups() {
	Event.observe(document, 'click', function(event) {
		$$('.why_register_popup').each(function(element) {
			// If the popup is showing
			if(element.visible()) { 
				// Hide popup if the mouse click is outside the popup window
				if(!mouseInZone(element.down('.tools_popup'), event)) {
					element.hide();
					return;
				}
			}
		});
		
		if($('js_share_popup') && $('js_share_popup').visible()) {
			if(!mouseInZone($('js_share_popup').down('.tools_popup'), event)) {
				$('js_share_popup').hide();
			}
		}
		if ( ! $('title_overview') ) {
			if($('js_embed_popup') && $('js_embed_popup').visible()) {
				if(!mouseInZone($('js_embed_popup').down('.tools_popup'), event)) {
					if(['input', 'label'].indexOf($(event.target).nodeName.toLowerCase()) == -1)
						$('js_embed_popup').hide();
				}
			}
		}
		
		if ( ! $$('.section_watch')[0] )
		{
			/*
				YouDo TODO: Please review: CT-added $$('.section_watch')[0] conditional
			*/
			if($('js_favourite_popup') && $('js_favourite_popup').visible()) {
				if(!mouseInZone($('js_favourite_popup').down('.tools_popup'), event)) {
					$('js_favourite_popup').hide();
				}
			}			
		}
		
	});
	
	if ($$('.why_register_button').length > 0 && $$('.why_register_popup').length > 0) {
		$$('.why_register_button').each(function(element) {
			Event.observe(element, 'click', function(e) {
				// Close all existing popups
				$$('.why_register_popup').each(function(element){
					element.hide();
				});
				
				var popup = undefined; 
				var parent = e.element(); // Get initial parent
				var i = 0; // Limit the loop
				// traverse up the dom looking for the popup.
				while(popup == undefined && i < 5) {
					popup = parent.next('.why_register_popup');
					parent = parent.up();
					i++;
				}
				// Show popup
				popup.style.display = 'block';
				Event.stop(e);
			});
		});
		
		$$('.js_register_popup_close').each(function(element) {
			Event.observe(element, 'click', function(e) {
				e.element().up('.why_register_popup').hide();
				Event.stop(e);
			});
		});
	}
		
	initFavouriteClose(); // This is moved into a dedicated function because IE6 doesn't honour event handlers set on DOM nodes near hotswapped content, so we have
	// to be able to refire this code when the popup is shown.
	
	if ($('js_embed_popup') && $$('.add_embed')) {
    
 		if ( $$('.section_watch')[0] ) //Tabs for Favourite/Share/Email/Badge It
		{
			// new style
			$$('.add_embed').each(function(element) {
				Event.observe(element, 'click', function(e){
					
					// Toggle widgets
					$('js_embed_popup').toggle();
					$$('.embed-simple')[0].toggle();
					// Update img src attribute
					$('tool_button_option').down().down('img').src = $('js_embed_popup').visible() ? '/resources/images/ui/buttons/button_options_bg_d8e0e2_down_active.gif' : '/resources/images/ui/buttons/button_options_bg_d8e0e2_up_off.gif';
					// Add/Remove classnames
					
					if ($('js_embed_popup').visible()) {
						$('tool_button_option').removeClassName('tool_button_options_up');
						$('tool_button_option').addClassName('tool_button_options_down');
					} else {
						$('tool_button_option').addClassName('tool_button_options_up');
					 	$('tool_button_option').removeClassName('tool_button_options_down');
					}
			
					Event.stop(e);
				});	
				Event.observe(element, 'mouseover', function(e) {
					$('tool_button_option').down().down('img').src = $('js_embed_popup').visible() ? '/resources/images/ui/buttons/button_options_bg_d8e0e2_down_hover.gif' : '/resources/images/ui/buttons/button_options_bg_d8e0e2_up_hover.gif';
					Event.stop(e);
				});
				Event.observe(element, 'mouseout', function(e) {
					$('tool_button_option').down().down('img').src = $('js_embed_popup').visible() ? '/resources/images/ui/buttons/button_options_bg_d8e0e2_down_active.gif' : '/resources/images/ui/buttons/button_options_bg_d8e0e2_up_off.gif';
					Event.stop(e);
				});
				/*
				Event.observe(element, 'mouseup', function(e) {
					$('tool_button_option').down().down('img').src = $('js_embed_popup').visible() ? '/resources/images/ui/buttons/button_options_bg_d8e0e2_down_off.gif' : '/resources/images/ui/buttons/button_options_bg_d8e0e2_up_off.gif';
					Event.stop(e);
				});
				*/		
			});
				
		}		
		else
		{			
      //old style     
    Event.observe('add_embed', 'click', function(e){
       $('js_favourite_popup').hide();
       $('js_embed_popup').show();
       Event.stop(e);
      });    
      Event.observe('js_embed_popup_close', 'click', function(e){
       $('js_embed_popup').hide();     
       Event.stop(e);
      });
      Event.observe($$('#js_embed_popup .text_tab')[0], 'click', function(e){
       $('js_embed_popup').hide();
       Event.stop(e);
      });
		}			
		
	}
	
	if ($$('.selectable')[0]) {
		$$('.selectable').each(function(element){
		  Event.observe(element, 'mousedown', function(e){
		    element = this;
		    element.select();
		    Event.stop(e);
		  });
		});
	}

	if ($('js_share_popup') && $('add_share')) {
		Event.observe('add_share', 'click', function(e){
			$('js_favourite_popup').hide();
			$('js_share_popup').show();
			Event.stop(e);
		});
		Event.observe('js_share_popup_close', 'click', function(e){
			$('js_share_popup').hide();
			$('js_share_popup').removeClassName('long');
			$('js_share_popup').removeClassName('invalid');
			$('js_share_form_tag').descendants().each(function(d) {
				d.removeClassName('invalid');
			});
			
			$$('#js_share_form_tag .form_validationerror').each(function(element){
				element.hide();
			});
			Event.stop(e);
		});
		Event.observe($$('#js_share_popup .text_tab')[0], 'click', function(e){
			$('js_share_popup').hide();
			$('js_share_popup').removeClassName('long');
			Event.stop(e);
		});
		Event.observe('js_share_form_show', 'click', function(e){
			$('js_share_form').show();
			$('dyn_email_friend_popup_thankyou').hide();
			$('dyn_email_friend_popup_error').hide();
			$('js_share_popup').addClassName('long');
			
			// AK: auto clearing form fields
			$('emailfriend_email').onfocus = function() {
				if (this.value == 'Email address') this.clear();;
			}
			$('emailfriend_email').onblur = function() {
				if (!this.present()) this.value= "Email address";
			}
			$('emailfriend_comments').onfocus = function() {
				if (this.value == 'Enter your message here.') this.clear();;
			}
			$('emailfriend_comments').onblur = function() {
				if (!this.present()) this.value= "Enter your message here.";
			}
			$('emailfriend_sender').onfocus = function() {
				if (this.value == 'Your name') this.clear();;
			}
			$('emailfriend_sender').onblur = function() {
				if (!this.present()) this.value= "Your name";
			}
			// end auto clearing
			
			Event.stop(e);
		});
		Event.observe('dyn_email_friend_cancel', 'click', function(e){
			$('js_share_form').hide();
			$('js_share_popup').removeClassName('long');
			$('js_share_form_tag').descendants().each(function(d) {
				d.removeClassName('invalid');
			});
			
			$$('#js_share_form_tag .form_validationerror').each(function(element){
				element.hide();
			});
			Form.reset('js_share_form_tag');
			Event.stop(e);
		});
	}
	
	// select embed code (note: we can't make this a textarea because of the styling requirements)
		// using up and down events to capture dragging
	if ($$('.selectable_code')[0]) {
		$$('.selectable_code').each(function(element){
			Event.observe(element, 'mousedown', function(e){
				element = this;
				if (document.selection) {
					//Portion for IE
					var div = document.body.createTextRange();
					div.moveToElementText(element);
					div.select();
				} else {
					//Portion for FF
					var div = document.createRange();
					div.setStartBefore(element);
					div.setEndAfter(element);
					window.getSelection().addRange(div);
				} 
				Event.stop(e);
			});
			
			Event.observe(element, 'mouseup', function(e){
				element = this;
				if (document.selection) {
					//Portion for IE
					var div = document.body.createTextRange();
					div.moveToElementText(element);
					div.select();
				} else {
					//Portion for FF
					var div = document.createRange();
					div.setStartBefore(element);
					div.setEndAfter(element);
					window.getSelection().addRange(div);
				} 
				Event.stop(e);
			});
		});
	}
	
}

function initFavouriteClose() { // This is moved into a dedicated function because IE6 doesn't honour event handlers set on DOM nodes near hotswapped content
	if ($('js_favourite_popup') && $('add_favourite') && $('js_favourite_popup_close')) { /* YouDo: please review CT-added conditional for close button */
		Event.observe('js_favourite_popup_close', 'click', function(e){
			$('js_favourite_popup').hide();
			Event.stop(e);
		});
		Event.observe($$('#js_favourite_popup .text_tab')[0], 'click', function(e){
			$('js_favourite_popup').hide();
			Event.stop(e);
		});
	}
}

//This should really be extrapolated out into controller-specific JS
var thumbinitnext = function(e) {
	slideNext(e);
};
var thumbinitprev = function(e) {
	slidePrev(e);
};
var returnFalse = function(e) {
	Event.stop(e);
}

function initForms() { //This function applies action handlers to forms!
	$$('form').each(function(form) {
		Element.extend(form); //For IE's benefit. Sigh.
		if (form.up().className != 'form_1') {
			return;
		}
		form.getElementsBySelector('input').each(function(s) {
			if (s.type == 'radio' || s.type == 'checkbox' || s.type == 'file' || s.className == 'upload') {
				return;
			}
			$(s).observe('focus', function() { makeActive(s) });
			$(s).observe('blur', function() { dropActive(s) });
		});
		// Apparently we don't want textareas doing this
		// form.getElementsBySelector('textarea').each(function(s) {
		// 	$(s).observe('focus', function() { makeActive(s) });
		// 	$(s).observe('blur', function() { dropActive(s) });
		// });

	});
	
}
function makeActive(s) {
	if (s.up().className == 'fieldWithErrors') { 
	  s.up(2).className = 'active';
	  return;
	} else if (s.up(1).className == 'complete') {
	  return;
	}
	s.up(1).className = 'active';
}
function dropActive(s) {
	if (s.up().className == 'fieldWithErrors') {
	  s.up(2).className = 'invalid';
	} else if (s.up(1).className == 'complete') {
	  return;
	}
	s.up(1).className = '';
}


function initGallery() {
	if (!$('js_image_thumbnails')) {
		return false;
	}
	
	document.getElementsByClassName('gallery_thumbnails')[0].addClassName('enabled');
	$('js_image_thumbnails').style.overflow = "hidden";
	// $('nextprev').style.display = 'block';
	if ($('js_image_thumbnails')) {
		$('js_image_thumbnails').getElementsBySelector('a.image_wrapper').invoke('observe', 'click', function(e) {
			
			$('js_image_thumbnails').getElementsBySelector('a.image_wrapper').each(function(ele){
				Element.removeClassName(ele, 'active');
			});
			
			if (e.target != null) {
				Element.addClassName(Element.extend(e.target).up(), 'active');
				gallerySelectImage(Event.element(e).next());
			} else {
				Element.extend(e.srcElement);
				if (Event.element(e).tagName == 'SPAN') {
					Element.addClassName(e.srcElement.up(), 'active')
					gallerySelectImage(Event.element(e).next());
				} else {
					Element.addClassName(e.srcElement, 'active')
					gallerySelectImage(Event.element(e));
				}
				 //This is for IE. e.target is always null
			}
			Event.stop(e);
		});
	}
	//portal is 825px wide
	//Handles the sliding thumbnail yayness
	if ($('slide_next')) {
		$('slide_next').observe('click', thumbinitnext);
		$('slide_previous').observe('click', thumbinitprev);
	}

}
function galleryPaginator(direction, currentID, index) {
	if (direction == 'next') {
		var length = $('slider').getElementsByClassName('image_border_2').length;
		
		if ($('slider').getElementsByClassName('image_border_2')[index + 1] == null) {
			return false;
		}
		
		var id = $('slider').getElementsByClassName('image_border_2')[index + 1].down('img').title;
		
		$('js_image_full_container').getElementsBySelector('div.surround').each(function(el) {
			el.style.display = "none";
		});
		
		$('slider').getElementsByClassName('image_border_2')[index].down('a').removeClassName('active');
		
		// id = currentID + 1;
		index = index + 1;
		if ($('js_image_full_' + id).empty()) {
			new Ajax.Updater('js_image_full_' + id , '/gallery/get_image?image_id=' + id + '&index=' + index + '&length=' + length, {
		        method: 'get'
		    });
		}
		$('js_image_full_' + id).style.display = '';
		
		$('slider').getElementsByClassName('image_border_2')[index].down('a').addClassName('active');
	} else {
		var length = $('slider').getElementsByClassName('image_border_2').length;
		if ($('slider').getElementsByClassName('image_border_2')[index - 1] == null) {
			return false;
		}
		var id = $('slider').getElementsByClassName('image_border_2')[index - 1].down('img').title;
		$('js_image_full_container').getElementsBySelector('div.surround').each(function(el) {
			el.style.display = "none";
		});
		
		$('slider').getElementsByClassName('image_border_2')[index].down('a').removeClassName('active');
		
		// id = currentID + 1;
		index = index - 1;
		if ($('js_image_full_' + id).empty()) {
			new Ajax.Updater('js_image_full_' + id , '/gallery/get_image?image_id=' + id + '&index=' + index + '&length=' + length, {
		        method: 'get'
		    });
		}
		$('js_image_full_' + id).style.display = '';
		
		$('slider').getElementsByClassName('image_border_2')[index].down('a').addClassName('active');
	}
}

// WHILE these slide functions are running, their onclick is replaced with returnFalse, which simply terminates any clicks. Sorry for the confusing.
function slideNext(e) {
	$('slide_next').stopObserving('click', thumbinitnext);
	$('slide_next').observe('click', returnFalse);
	
	if ($('slider').offsetLeft < -($('slider').offsetWidth - 825) && $('slider').style.left != '0px' && $('slider').style.left != '') {
		$('slide_next').stopObserving('click', returnFalse);
		$('slide_next').observe('click', thumbinitnext);
		Event.stop(e);
		return false;
	}
	new Effect.Move($('slider'), {
		duration: 0.7, 
		x: -200, 
		y: 0,
		mode: 'relative',
		afterFinish: function() {
			$('slide_next').stopObserving('click', returnFalse);
			$('slide_next').observe('click', thumbinitnext);
		}
	});
	
	Event.stop(e);
}

function slidePrev(e) {
	$('slide_previous').stopObserving('click', thumbinitprev);
	$('slide_previous').observe('click', returnFalse)
	
	if ($('slider').style.left == '0px' || $('slider').style.left == "" || $('slider').offsetLeft > 0) {
		$('slide_previous').stopObserving('click', returnFalse)
		$('slide_previous').observe('click', thumbinitprev);
		Event.stop(e);
		return false;
	}
	new Effect.Move($('slider'), {
		duration: 0.7, 
		x: 200, 
		y: 0, 
		mode: 'relative',
		afterFinish: function() {
			$('slide_previous').stopObserving('click', returnFalse)
			$('slide_previous').observe('click', thumbinitprev);
		}
	});
	
	Event.stop(e);
}

//Admin UI stuff
function cleanSelect() {
    e = $('available_foos');
    foo = $('associated_id').options;
    for (var a = 0; a < foo.length; a++) { 
        if (foo[a].innerHTML == e.value) {
            foo[a].selected = 'selected';
        }
    }           
}

function gallerySelectImage(image) {
	id = image.title;
	index = image.up().title;
	var length = $('slider').getElementsByClassName('image_border_2').length;
	$('js_image_full_container').getElementsBySelector('div.surround').each(function(el) {
		el.style.display = "none";
	});
	if ($('js_image_full_' + id).empty()) {
		new Ajax.Updater('js_image_full_' + id , '/gallery/get_image?image_id=' + id + '&index=' + index + '&length=' + length, {
	        method: 'get'
	    });
	}
	$('js_image_full_' + id).style.display = '';
}

function exploreResultStyleToggler() {
	alert('asdasdasd');
	document.getElementsByClassName('tools').each(function(s) {
		s.style.display="";
	});
	
	Event.observe($('galleryToggle'), 'click', function(e) {
		
		document.getElementsByClassName('galleryview')[0].style.display = 'block';
		document.getElementsByClassName('listview')[0].style.display = 'none';
		
		Event.stop(e);
	});
	
	Event.observe($('listToggle'), 'click', function(e) {
		document.getElementsByClassName('listview')[0].style.display= 'block';
		document.getElementsByClassName('galleryview')[0].style.display= 'none';
		Event.stop(e);
	});
}

function registerAutoComplete() {
	if ($('user_login').value == "" || 
	($('user_login').value == " ") || 
	($('user_login').value == $('user_first_name').value) || 
	($('user_login').value == $('user_last_name').value))
{
		firstName = $('user_first_name').value.replace(/[^A-Za-z_0-9]/g, "");
		lastName = $('user_last_name').value.replace(/[^A-Za-z_0-9]/g, "");
		
		$('user_login').value = firstName + lastName;
	}
}

function highlightExplore(el, az) {
	Element.extend(el); //This makes stuff work in IE.
	
	if (!az) {
		if (el.up(1).getElementsByClassName('active')[0]) {
			el.up(1).getElementsByClassName('active')[0].removeClassName('active');
		}
	} else {
		if (el.up(2).getElementsByClassName('active')[0]) {
			el.up(2).getElementsByClassName('active')[0].removeClassName('active');
		}
	}
	
	if (el.up(2).id == 'explore_filter_1') {
		$('explore_filter_2').innerHTML = "";
		$('explore_filter_3').innerHTML = "";
		$('explore_filter_4').innerHTML = "";
	} else if (el.up(2).id == 'explore_filter_2') {
		$('explore_filter_3').innerHTML = "";
		$('explore_filter_4').innerHTML = "";
	} else if (el.up(2).id == 'explore_filter_3' )
		$('explore_filter_4').innerHTML = "";
	
	el.up().addClassName('active');
}

// function uploadImage(id, path) {
// 	var name = "title_image_" + id;
// 		
// 	var remove = "<a onclick=\"new Ajax.Request('/admin_title/remove_title_thumbnail/' + id, {asynchronous:true, evalScripts:true, onSuccess:function(request){removeImage(" + id + "); return false;}}); return false;\" href=\"#\">Remove Image</a>";
// 	document.getElementById(name).innerHTML = remove + "<img width='100px' border='0px' src='" + path + "' />&nbsp;";
// }

function toggleAdminField(el) {
	var parent = el.up(1).next();
	
	if (parent.style.display == 'none') {
		parent.show();
	} else {
		parent.hide();
	}
}
 
function addTitleRelation (id, name) {
	var link = document.createElement('a');
	link.href = "#"
	link.innerHTML = "Remove Relation";
	link.onclick = function(id) {
		new Ajax.Request('/admin_title/remove_title_relation/' + id,{ 
						asynchronous:true, 
						evalScripts:true, 
						onSuccess:function(request){removeRelation(id);}});
		return false;
	}
	
	new Insertion.Bottom('related_titles_list_' + id, '<li id=\"related_title_' + id + '\">' + name + '&nbsp;&nbsp;</li>');
	$('related_titles_list_' + id).immediateDescendants()[$('related_titles_list_' + id).immediateDescendants().length - 1].appendChild(link); 
}

function removeRelation (id) {
	$('related_title_' + id).remove();
}

/*THIS FUNCTION ACCESSED BY POPUP WINDOW UPLOADERS and calls back to the above function*/
function title_relation_callback(id, name) {
	self.opener.addTitleRelation(id, name);
	self.close();
}

// function upload_image_callback(id, path) {
// 	self.opener.uploadImage(id, path);
// 	self.close();
// }

function removeImage(id) {
	var name = "title_image_" + id;
	document.getElementById(name).innerHTML = "<a onclick=\"window.open(this.href,'Upload Image','height=300,width=600');return false;\" href=\"/admin_title/upload_image?title_id=" + id + "\">Add Image</a>"
}


/*These methods clean up TinyMCE and ActiveScaffold so things will work smoothly.*/

function closeRow(a, fields) {
	for (var n = 0; n < fields.length; n++) {
    	tinyMCE.execCommand("mceRemoveControl", false, fields[n].id);
	}
}

/*Call setupTinyMCE() in any custom partial containing a TinyMCE textarea. fieldname = the id tag of the relevant field sans the appended id, id is the object id in question.*/
function setupTinyMCE(id, object) {
    //  var fields = document.getElementById('admin_' + object + '-list-' + id + '-row').nextSiblings()[0].getElementsByClassName('tinyMice');
    var fields = document.getElementsByClassName('tinyMice');
	for (var n = 0; n < fields.length; n++) {
		tinyMCE.execCommand ("mceAddControl", false, fields[n].id);
	}
    if (document.getElementById('admin_' + object + '-update-' + id + '-form')) {
			
        document.getElementById('admin_' + object + '-update-' + id + '-form').onsubmit = function() {
            tinyMCE.triggerSave(true,true);
            for (var n = 0; n < fields.length; n++) {
                tinyMCE.execCommand("mceRemoveControl", false, fields[n].id);
          }
        }
    }
    if (document.getElementById('admin_' + object + '-list-' + id + '-row')) {
        var close = document.getElementById('admin_' + object + '-list-' + id + '-row').nextSiblings()[0].getElementsByClassName('inline-adapter-close')[0];
        close.observe('click', function() {closeRow(this, fields);});
    }    
  	
}


function setupTinyMCECreate(object) {
	
    if (document.getElementById('admin_' + object + '-create--form')) {
        
        var fields = document.getElementById('admin_' + object + '-create--form').getElementsByClassName('tinyMice');
        for (var n = 0; n < fields.length; n++) {
            tinyMCE.execCommand("mceAddControl", false, fields[n].id);
        }

        document.getElementById('admin_' + object + '-create--form').onsubmit = function() {
            tinyMCE.triggerSave(true,true);
            for (var n = 0; n < fields.length; n++) {
                tinyMCE.execCommand("mceRemoveControl", false, fields[n].id);
            }
        }

        var close = document.getElementById('admin_' + object + '-create--form').parentNode.getElementsByClassName('inline-adapter-close')[0];
        close.observe('mouseup', function() {closeRow(this, fields);});
        
    }
}

function show_hide_role_description() {
    var current_select = document.getElementById('record_role_type');
    var desc_field = document.getElementById('record_role_character_name');
    if(current_select.value == 'Actor' || current_select.value == 'Other') {
        desc_field.style.display = '';
    } else {
        desc_field.style.display = 'none';
    }
}


// show or hide fields based on the title_type field.
// This code originally supported just series and title types. It's been quickly
// patched to handle artist and track types
function show_hide_title_type() {
    var current_select = document.getElementById('record_title_type');
    //var children_field = document.getElementById('record_children');
    var non_series_fields = document.getElementsByClassName('non-series');
    var series_fields = document.getElementsByClassName('series');
   
    if(current_select.value == 2) { // Series
        // children_field.style.display = '';
        for (i=0; i<non_series_fields.length;i++) {
            non_series_fields[i].style.display = 'none';
        }
        for (i=0; i<series_fields.length;i++) {
            series_fields[i].style.display = '';
        }        
        
    } else {        
        for (i=0; i<series_fields.length;i++) {
            series_fields[i].style.display = 'none';
        }
        for (i=0; i<non_series_fields.length;i++) {
            non_series_fields[i].style.display = '';
        }

        //we need to hide/show some specific non-title fields
        if (al = document.getElementById('track_album_name')) {
            if (current_select.value == 3) {
               al.style.display = '';
            } else {
                al.style.display = 'none';
            }
        }
        if (epnum = document.getElementById('title_episode_number')) {
            if (current_select.value == 0) {
               epnum.style.display = '';
            } else {
                epnum.style.display = 'none';
            }
        }        
        if (current_select.value == 4 && document.getElementById('series_artist_children')) {
            document.getElementById('series_artist_children').style.display = '';
        }
        
    }
    
}





//This function handles toggling between tabs in the Watch section of the frontend.
//IE is retarded and we need to extend elements we are trying to use methods on manually. Don't know why. At least it allows us to chain. -Will
function tabRowToggle(slug) {
	Element.extend($('tab_row')).getElementsByClassName('active')[0].className = ""; 
	Element.extend($('tab_row').getElementsByClassName('select')[0]).removeClassName('select');	
	Element.extend(document.getElementsByClassName('menu_' + slug)[0]).addClassName('select');
	document.getElementsByClassName('menu_' + slug)[0].down('span').className = "active";
}

var max_image_tag_id = 0;
function add_image_tag(parent_id, ul_id){
    if($(parent_id).value != ''){
        new Insertion.Bottom(ul_id, '<li id="new_tag_' + max_image_tag_id + '">' + $(parent_id).value + '&nbsp;&nbsp;<a href="#" onclick="$(\'new_tag_' + max_image_tag_id + '\').remove(); return false;" >Remove</a><input type="hidden" name="image_tags[]" value="' + $(parent_id).value + '" /></li>');
        max_image_tag_id = max_image_tag_id + 1;
        $(parent_id).value = '';
    }
}

/* dynamically choose which url to send to */
function load_explore_page(result_div, page_number){
    var dest = $('list_url_page_' + page_number).value;
    /* removed explore_galleryview after rev 1972 */
    
    new Ajax.Updater(result_div, dest, {asynchronous:true, evalScripts:true, onLoaded:function(request){scrollToElement('widget_explore');}}); 
}

/* scroll window to have this element at top of screen */
function scrollToElement(element_id){
    var top = $(element_id)
    if (top){
        var pos = findPos(top);
        window.scrollTo(pos[0], pos[1]);
    }
}

/* find coordinates of element [x,y] */
function findPos(obj) {    
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }
    return [curleft,curtop];
}

function adminImageUpload() {
    if($('image_label').value.length > 0){
        var form_el = $('image_upload_form');
        form_el.submit();
    } else {
        alert("You must specify a label to upload an image");
        return false;
    }
}

function operaFix() {
	if (document.getElementsByClassName('opera').length > 0) {
		if (document.getElementsByClassName('opera')[0].style.position == "") {
			document.getElementsByClassName('opera')[0].style.position="relative";  /* Opera redraw bug fix */
		} else {
			document.getElementsByClassName('opera')[0].style.position="";
		}
	}
}

function ffmacFix(type) {
	if ((whichbrowser.isWin==false) && (whichbrowser.isFirefox==true) && (whichbrowser.versionMajor>="2")) {
		if (document.getElementsByClassName('section_home').length > 0) {
			generateiframe($('zone_header').getElementsByClassName('wrapper')[0], type); // from css_helpers.js
		}
	}
}

// Image hovers for image_border_2
function imagehovers() {
	
	// Main over state for images
	if($$('.image_border_2')[0]) {
		$$('.image_border_2 a').each(function(imagelink) {
			Event.observe(imagelink, 'mouseover', function(){
				this.addClassName('over');
			});
			Event.observe(imagelink, 'mouseout', function(){
				this.removeClassName('over');
			});
		});
	}
	
	// Associate adjacent links with image hover
	if($$('.image_border_2')[0]) {
    $$('.image_border_2').each(function(image) { // cycle through each image
			// Table cell version
			if(image.up('td')) { // search for adjacent title link
				if(image.up('td').adjacent('.title_link a').length>0) {
					Event.observe(image.up('td').adjacent('.title_link')[0].down('a'), 'mouseover', function() {
						image.down(1).addClassName('over');
					});
					Event.observe(image.up('td').adjacent('.title_link')[0].down('a'), 'mouseout', function(){
						image.down(1).removeClassName('over');
					});	
				}
			} else {
				// Default version
				if(image.adjacent('.title_link a').length>0) { // search for adjacent title link
						Event.observe(image.adjacent('.title_link')[0].down('a'), 'mouseover', function() {
							image.down(1).addClassName('over');
						});
						Event.observe(image.adjacent('.title_link')[0].down('a'), 'mouseout', function(){
							image.down(1).removeClassName('over');
						});
				}
			}			
    });
  }
  
	if ($$('.section_watch #widget_usertools')[0]) { // rollovers
		// Swap on over state
		if ($$('#widget_usertools .twitter')[0]) {
			Event.observe($$('#widget_usertools .twitter')[0], 'mouseover', function(){
				$$('#widget_usertools .twitter img')[0].src = '/resources/images/ui/icons/icon-twitter.gif';
			});
			Event.observe($$('#widget_usertools .twitter')[0], 'mouseout', function(){
				$$('#widget_usertools .twitter img')[0].src = '/resources/images/ui/icons/icon-twitter-inactive.gif';
			});
		}
		if ($$('#widget_usertools .stumble')[0]) {
			Event.observe($$('#widget_usertools .stumble')[0], 'mouseover', function(){
				$$('#widget_usertools .stumble img')[0].src = '/resources/images/ui/icons/icon-stumbleupon-active.gif';
			});
			Event.observe($$('#widget_usertools .stumble')[0], 'mouseout', function(){
				$$('#widget_usertools .stumble img')[0].src = '/resources/images/ui/icons/icon-stumbleupon-inactive.gif';
			});
		}
		if ($$('#widget_usertools .facebook')[0]) {
			Event.observe($$('#widget_usertools .facebook')[0], 'mouseover', function(){
				$$('#widget_usertools .facebook img')[0].src = '/resources/images/ui/icons/icon-facebook.gif';
			});
			Event.observe($$('#widget_usertools .facebook')[0], 'mouseout', function(){
				$$('#widget_usertools .facebook img')[0].src = '/resources/images/ui/icons/icon-facebook-inactive.gif';
			});
		}		
	} 
}

// Image preloaders
function preloadimages() {
  
	if ($$('.section_home')[0]) { 
		
		var cssimagearray = new Array(
			"/resources/images/ui/homepage/panel-tab-2-on.gif",
			"/resources/images/ui/homepage/panel-tab-1-off.gif",
			"/resources/images/ui/homepage/nav-panels-right-hover.gif",
			"/resources/images/ui/homepage/nav-panels-right-inactive.gif",
			"/resources/images/ui/homepage/nav-panels-left-hover.gif",
			"/resources/images/ui/homepage/nav-panels-left-inactive.gif",
			"/resources/images/ui/homepage/nav-panels-item-hover.gif",
			"/resources/images/ui/homepage/nav-panels-item-active.gif"
		);
		for(var j = 0; j<cssimagearray.length; j++){ 
			var img = new Image();
			img.src = cssimagearray[j];
		}
  } else if ($$('.section_watch #widget_usertools')[0]) { // rollovers
		var preloadimagearray = new Array(
			"/resources/images/ui/icons/icon-stumbleupon-active.gif",
			"/resources/images/ui/icons/icon-twitter-active.gif",
			"/resources/images/ui/icons/icon-facebook-active.gif"
		);
		for(var j = 0; j<preloadimagearray.length; j++){ 
			var img = new Image();
			img.src = preloadimagearray[j];
		}
		
	} 
	var cssimagearray = new Array(
			"/resources/images/ui/imageborders/img-bdr-2-mediumsmall-profile-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-mediumsmall-screentalk-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-mediumsmall-screentalk-play-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-mediumsmall-title-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-mediumsmall-title-play-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-quitesmall-profile-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-quitesmall-screentalk-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-quitesmall-screentalk-play-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-quitesmall-title-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-quitesmall-title-play-over.png",
			"/resources/images/ui/imageborders/img-bdr-2b-quitesmall-title-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-medium-profile-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-medium-screentalk-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-medium-screentalk-play-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-medium-title-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-medium-title-play-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-small-profile-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-small-screentalk-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-small-screentalk-play-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-small-title-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-small-title-play-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-thumbnail-profile-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-thumbnail-screentalk-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-thumbnail-screentalk-play-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-thumbnail-title-over.png",
			"/resources/images/ui/imageborders/img-bdr-2-thumbnail-title-play-over.png"
	);
	for(var j = 0; j<cssimagearray.length; j++){ 
			var img = new Image();
			img.src = cssimagearray[j];
	}
	
	imagehovers(); // call image hover listeners
}


function embedSizeChanged(e, width, height){
	//$(e).select('input').first().checked = true;
	
	$$('#embed_code span.embedWidth').each(function(e){
		$(e).innerHTML = width;
	});

	$$('#embed_code span.embedHeight').each(function(e){
		$(e).innerHTML = height;
	});
}

function embedBadgeSizeChanged(e, width, height, src){
	//$(e).select('input').first().checked = true;
  
	$$('.badge_sample').each(function(e) {
	  $(e).down('img').src = src;
  });
  
  $$('#embed_badge_code span.badgeSrc').each(function(e){
		$(e).innerHTML = src;
	});
	
	$$('#embed_badge_code span.badgeWidth').each(function(e){
		$(e).innerHTML = width;
	});

	$$('#embed_badge_code span.badgeHeight').each(function(e){
		$(e).innerHTML = height;
	});
}

function embedStartClipChanged(element){
	$$('#embed_code span.videoID').each(function(e){
			$(e).innerHTML = $(element).value;
	});
	
	$$('#embed_code span.clipText').each(function(e){
		$(e).innerHTML = 'Clip ' + $(element.selectedIndex + 1);
	});
}


// Closing the NZOS simple link popup - referenced in fckEditor iframe
var NzosLinkSimpleCommandRemove = function NzosLinkSimpleCommandRemove(element) {
	element = $(element);
    element.parentNode.removeChild(element);
}

// Adding the NZOS simple link - referenced in fckEditor iframe
var NzosLinkSimpleCommandSubmit = function NzosLinkSimpleCommandSubmit(element,inputelement,nzoslinktext) {
	// retrieve the editor instance
	var oEditor = FCKeditorAPI.GetInstance('DataFCKeditor'); // 
	var url = $(inputelement).getValue(); // get url
	url = url.replace('http://',''); // remove prefix (should we also remove other prefixes, eg https?)
	
	// send the editor the html for insertion
	if (nzoslinktext=='') nzoslinktext = url; // if they don't select any text, put the url in as the link text
	oEditor.InsertHtml('<a target="_blank" href=http://'+url+'>'+unescape(nzoslinktext)+'</a>'); // injects content back into the editor
	
	// remove the popup
	element = $(element);
    element.parentNode.removeChild(element);
}

// Add return key listener to submit
var NzosLinkSimpleCommandEnterSubmit = function NzosLinkSimpleCommandEnterSubmit(parentelement,inputelement,nzoslinktext) {
	Event.observe(inputelement, 'keyup', function(e){
		if (e.keyCode == Event.KEY_RETURN) {
			NzosLinkSimpleCommandSubmit(parentelement,inputelement,nzoslinktext);
			Event.stop(e);
		}
	});
}

/* Form auto clearing elements (jQuery style)
		 eg.
		 $('user_firstName').labelActsAsHint('Your first name');
		 $('password').labelActsAsHint();
------------------------------------------------------------- */	


Element.Methods.labelActsAsHint = function(input,labeltext) {
	if (input) {
    	var label = input.up(2).down('label');
		
		if (labeltext != null) {
			formvalue = labeltext;
		} else {
			var formvalue = input.value; // get default form value
		}
		input.removeClassName('active');
		label.removeClassName('active');
		
		if (input.value != formvalue) {
			input.addClassName('active');
		}
		//	label.addClassName('active');
		//}
		
		// IE wants to click the label, so let it
		label.onclick = function() {
			input.focus();
			input.addClassName('active');
		}
		
		// Focus
		input.onfocus = function() {
			label.addClassName('active');
			input.addClassName('active');
			if (input.value == formvalue) {
				input.value = ""; // clear
				label.addClassName('active').removeClassName('hastext'); 
			}
		}
		
		// Blur
		input.onblur = function() {
			if (input.value.empty()) {
        		label.removeClassName('active').removeClassName('hastext');  
				input.removeClassName('active');
			}
		}
		
		// Fade the label back if a field has text		
	    if (!input.value.empty()) {
	      label.addClassName('hastext');
	    }
	    // Fade the label back when the user starts to type		
	    input.onkeypress = function(){
	      label.addClassName('hastext');
	    }
		
	    return input;
	}
}

/*
 *  The following initSliders, sliderElementMethods and DownSlider are all used for
 *  sliding down effect required for title page redesign 2010 - 02. 
 * 
 *  Usage: $(dom_element).initSlider(dom_class_to_slide, duration_of_slide) - You can then call $(dom_element).slide()
 *    to slide then next dom_class element until there are none left to slide, at which point it
 *    will hide the closest .tool_button_show element.
 */

function initDownSliders() {
  // Initialise #related_titles_slider hyperlink to slider .related_titles class
  if($('related_titles_slider') != undefined) {
    $('related_titles_slider').initSlider({sliderClass:'related_titles', duration:1});
  }
  
  if($('comments_slider') != undefined) {
    $('comments_slider').initSlider({sliderClass:'comment_group', duration:1, buttonText:'comment', sliderElementsClass:'comment_liner'});
  }
}

// Methods required for slider
var downSliderElementMethods = {
  
  initSlider: function(element, options) {
    element = $(element);
    element.downSlider = new DownSlider(element, options);
    return element;
  },
  
  slide: function(element) {
    element = $(element);
    element.downSlider.execute();
    return element;
  }
};

// Class used to encapsulate all down slider information and execution.
function DownSlider(element, options) {
  this.sliderClass = options['sliderClass'];
  this.sliderElementsClass = options['sliderElementsClass'];
  this.sliderCount = 0;
  this.sliderItems = $$('.'+options['sliderClass']);
  this.element = element;
  this.duration = 1;
  this.buttonText = options['buttonText'];
  
  
  this.execute = function(element) {
    var sliderItem = this.sliderItems[this.sliderCount++];
    // Uses script.aculo.us SlideDown function
    // Doc: http://wiki.github.com/madrobby/scriptaculous/effect-slidedown
    if(sliderItem != undefined) {
      Effect.BlindDown(sliderItem,{ afterFinish: this.hide(), duration: this.duration});
    }
  }
  
  // Updates the slider button text or Hides the button depending on config.
  this.hide = function() {
    if(this.sliderItems[this.sliderCount] == undefined) {
      if(this.buttonText == undefined) {
        element.up('.tool_button_show').hide();
      } else {
        element.innerHTML = "";
        element.up('.tool_button_show').addClassName('tool_button_show_disabled');
        this.wrapElement();
      }
    } else {
      var sliderElementsRemaining = $(this.sliderItems[this.sliderCount]).select('.'+this.sliderElementsClass).length;  
      element.innerHTML = "Show " + sliderElementsRemaining.toString()  + " more " + this.pluralize(sliderElementsRemaining, this.buttonText);
      this.wrapElement();
    } 
  }
  
  this.wrapElement = function() {
    element.innerHTML = "<span><span><span><span>"+element.innerHTML+"</span></span></span></span>"
  }
  
  this.pluralize = function(count, word) {
    return (count > 1) ? word+'s' : word
  }  
}

Element.addMethods('a', downSliderElementMethods);
Element.addMethods();