// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

var thumbnail_suffixes = ['png', 'gif', 'jpg']
function validate_thumbnail_post(form) {
	var image = form.image.value;
	if (image.blank()) {
		Flash.error("Choose an image file to upload.")
		return false;
	}
	image = image.toLowerCase();
	for (var i=0;i<thumbnail_suffixes.length; i++) {
		if (image.endsWith('.'+thumbnail_suffixes[i])) {
			return true;
		}
	}
	Flash.error("Thumbnail image files must be one of: " + thumbnail_suffixes.join(', '));
	return false;
}

var switcher_control = {
	'overlays_being_watched':true,
	'hot_videos_being_watched':true
}

function switcher(class_name, flag) {switcher_control[class_name]=flag}


function switch_overlays(class_name) {
	if (switcher_control[class_name] == false) {return;}
	var elements = $$('.'+class_name);
	if (elements.size()==0)
		return
	var visible = $$('.'+class_name + '.being_shown');
	var index = 0;
	if (visible.size() != 0){
		if (navigator.appName=="Microsoft Internet Explorer")
	 		visible[0].hide({duration:0.5,queue:{position:'end', scope:class_name}});
		else
			visible[0].fade({duration:0.5,queue:{position:'end', scope:class_name}});
			
	  	index = elements.indexOf(visible[0]) +1;
	  	visible[0].removeClassName('being_shown');
	 }
	 
	if (index >= elements.size())
	 	index = 0;
	if (navigator.appName=="Microsoft Internet Explorer")
		elements[index].show({duration:0.5,queue:{position:'end', scope:class_name}});
	else
		elements[index].appear({duration:0.5,queue:{position:'end', scope:class_name}});
		
	elements[index].addClassName('being_shown');
}

function copyBadgeEmbed(contentString){
		var flash_div = $('flashcopier');
		if (!flash_div) {return;}
		flash_div.innerHTML = '';
		contentString = '<script type="text/javascript" src="'+contentString+'"></script>'
		var div_info = '<embed src="/swf/copy_bot.swf" FlashVars="clipboard='+encodeURIComponent(contentString)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		flash_div.innerHTML = div_info;
		
		new Effect.Parallel([
			new Effect.Highlight('badgeEmbed', {duration: 1}), 
			new Effect.Appear('copied', {
				beforeStart: function(effect){
					$('copyEmbedButton').hide();
				}})
				], { queue: {
						position: 'end',
						scope: 'copyscope'
					}
					});
		new Effect.Fade('copied', { 
			duration: 1, 
			afterFinish: function(effect){$('copyEmbedButton').show();}, 
			queue: { position: 'end', scope: 'copyscope' } 
		});
}

function refreshBadge() {
	var is_tall = $('badge_iframe').hasClassName('tall_badge');
	
	if(is_tall == true) {
		$('badge_iframe').removeClassName('tall_badge');
		$('badge_iframe').addClassName('wide_badge');
		$('badge_iframe').width = 414;
		$('badge_iframe').height = 145;
	}
	else {
		$('badge_iframe').removeClassName('wide_badge');
		$('badge_iframe').addClassName('tall_badge');
		$('badge_iframe').width = 157;
		$('badge_iframe').height = 399;
	}
	$('badge_iframe').contentWindow.location.reload(true);
}

function badgeUpdateFailure() {
	oops();
	$('iframe_spinner').hide();
}

function badgeFrameLoaded() {
	$('iframe_spinner').hide();
	$('badge_iframe').show();
	
}

//override inline
var ChannelEvents = {
	overlayAddedToChannel:		function (overlayId, channelId) {window.location.reload()},
	overlayRemovedFromChannel:  function(overlayId, channelId) {window.location.reload()}
}

var UserProducts = {
		
	_links : ['createLink', 'editLink', 'deleteLink'],
		
	//Private
	
	_show_hide: function(ids, show, use_visibility) {
		if( ids == undefined )
		  return;
		if( show == undefined )
		  show = true;
		  
		if (use_visibility == undefined) 
		  use_visibility = false
		  
		
		for (var i=0; i< ids.size(); i++) {
			elem = $(ids[i])
			if (elem) {
				if (elem.hasClassName('ignoreShow')) { return; }

				if (use_visibility) {
					elem.setStyle(show ? 'visibility:visible' : 'visibility:hidden')
				} else {
					show ? elem.show() : elem.hide();
				} 
			}	
		}
	},
	
	_show_page: function(page) {
		if (page == undefined)
			return;
		
		pages = [$('show'), $('edit'), $('new')]
		
		elem = $(page)
		
		if (elem) {
			elem.show();
			for (var i = 0; i < pages.size(); i++) {
				if (pages[i] != elem) {if (pages[i]){pages[i].hide()}}
			}
		}
		
		if (elem && page != 'show') {
			form = $(page+'Form');
			if(form) {
				form.focusFirstElement();
			}
		}
	},
	
	_validate_form: function(form) {
		var messages = [];
		
		this._not_blank(form["product[title]"]		, "<p>The Name can't be blank<p>"				, messages)
		if (form.id != 'edit') {
			this._not_blank(form["product[url]"]	, "<p>The Product URL can't be blank</p>"		, messages)
		}
		this._not_blank(form["product[image_url]"]	, "<p>The Image URL can't be blank<p>"			, messages)
		
		if (messages.length > 0) {
			Flash.error(messages.join(' '));
			return false;	
		}
		return true;
	},
	
	_not_blank: function(form_input, message, messages) {
		if (form_input.value.trim() == '') {
			messages.push(message);
			//TODO in_form.addClassName('formError');
		}
	},
	
	_form_buttons: function(show) {
		this._show_hide(['formButtons'], show, true); 
	},
	
	//Public
	
	on_new: function() {
		this._show_hide(this._links, false, true);
		this._show_hide(['productImage', 'productGraphs'], false, true);
		this._show_page('new');
		this._form_buttons(true);
		submit = $('submitButton');
		submit.value = 'CREATE'
		submit.onclick = this.on_new_save
		return false;
	},
	
	on_edit: function() {
		this._show_hide(this._links, false, true)
		this._show_hide(['productImage','productGraphs'], true, true)
		this._show_page('edit');
		this._form_buttons(true);
		submit = $('submitButton');
		submit.value = 'SAVE'
		submit.onclick = this.on_edit_save
		return false;
	},
	
	on_delete:function() {
		
	},
	
	no_op: function() {return false;},
	
	on_cancel:function() {
		this._show_hide(this._links, true, true)
		this._show_page('show');
		if (document.editForm) {
			this._show_hide(['productImage','productGraphs'], true, true)
		}
		this._form_buttons(false);
		return false;
	},
	
	on_new_save: function() {
		form = document.newForm
		if (form) {
			if (UserProducts._validate_form(form)) {
				form.onsubmit()
			}
		}
	},
	
	on_edit_save: function() {
		form = document.editForm
		if (form) {
			if (UserProducts._validate_form(form)) {
				form.onsubmit()
			}
		}
	}
}

if (!window.OVERLAYTV_HACKS) (function () {
	var spinners = {}
	var sp = '/images/template/spinner.gif'
	function ImageSpinnerImpl(image_id) {
		this.image_id = image_id
		this.orig_image_src = $(this.image_id).src
	}
	ImageSpinnerImpl.prototype = {
		stop: function(){
			$(this.image_id).src = this.orig_image_src
		},
		start: function() {
			$(this.image_id).src = sp;
		}
	}
	var spinner_impl = ImageSpinnerImpl
	OVERLAYTV_HACKS = {
		spinner_for : function(image_id) {
			var spin = spinners[image_id]
			if (!spin) {
				spin = new spinner_impl(image_id)
				spinners[image_id] = spin
			}
			return spin
		}
	}
	var self = OVERLAYTV_HACKS
})();
if (!window.OTV_FAQ) (function() {
	var setup_faq = function() {
		OTV_FAQ.clear_all_faq();
		$$('div.question a').each(function(s) { Event.observe(s,'click', open_faq); });
	}
	var open_faq = function(event) {
		var current = event.element().up('div.faq');
		Effect.toggle(current.down('div.answerHolder'), 'blind', {duration:'0.25'});
		Event.stop(event);
	}
	OTV_FAQ = {
		clear_all_faq: function() {$$('div.answerHolder').each(Element.hide);}
	}
	var self = OTV_FAQ;
	Event.observe(window, 'load', setup_faq);
})();

function show_login() {
  safe_show('login');
  safe_hide('signup');
}

function show_signup() {
  safe_show('signup');
  safe_hide('login');
}


function confirm_load_url(message, urlOnOk) {
	var answer = confirm (message)
	if (answer && urlOnOk) {
		window.location.href = urlOnOk;
	}
}


// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
	var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," "));
	var now = new Date();
  var diff = Math.abs(((now.getTime() - date.getTime()) / 1000) + (date.getTimezoneOffset() * 60));
  var day_diff = Math.floor(diff / 86400);
	
  if ( isNaN(day_diff) || day_diff <0 /*|| day_diff>= 31*/ )
	  return;
  return day_diff == 0 && (
	  diff <60 && "seconds ago" ||
    diff <120 && "1 minute ago" ||
    diff <3600 && Math.floor( diff / 60 ) + " minutes ago" ||
    diff <7200 && "1 hour ago" ||
    diff <86400 && Math.floor( diff / 3600 ) + " hours ago") ||
    day_diff == 1 && "Yesterday" ||
		day_diff <7 && day_diff + " days ago" ||
    day_diff <49 && Math.ceil( day_diff / 7 ) + " weeks ago" ||
	  day_diff <365 && Math.floor(day_diff / 30) + " months ago" ||
		Math.floor(day_diff / 365) + " years ago";
}

function reset_form(id)
{
  $(id).reset();
}

//common oops message when ajax call fails (usually server not available)
function oops() {Flash.error("We had a problem doing that for you.<br/>Please try again or contact us if you continue having problems.");}

function get_caching_cookie_data() {
	return JSON.parse(unescape(Cookie.get("caching")));
}

function cookie_has_role() {
	return get_caching_cookie_value('role') == 'true'
}

function get_caching_cookie_value(key) {
	var data = get_caching_cookie_data();
	if (!data) return false;
	if (!data[key]) return false;
	return unescape(data[key].toString().gsub(/\+/, ' '));
}

function set_from_cookie(key, element) {
  var page_element = $(element);
  var content = get_caching_cookie_value(key);
  if (content) page_element.innerHTML = unescape(content);
}

function get_cookie_username() {
	return get_caching_cookie_value('welcome');
}

function cookie_check_logged_in() {
	var logged_in_data = get_caching_cookie_data();
	return logged_in_data && logged_in_data["logged_in"];
}

function logged_in_if_else() {
  if(cookie_check_logged_in())
  {
    safe_hide('signup_wrapper');
    safe_hide('login_wrapper');
  }
  else
  {
    safe_hide('welcome_wrapper');
    safe_hide('logout_wrapper');
    safe_hide('mypage_logged_in');
    safe_show('signup_wrapper');
    safe_show('login_wrapper');
  }
}

function safe_show_hide(elem, show) {
  if ($(elem)) {
    if (show) {
      $(elem).show();
    } else {
      $(elem).hide();
    }
  }
}

function safe_show(elem) {
  safe_show_hide(elem, true);
}

function safe_hide(elem) {
  safe_show_hide(elem, false);
}

function user_login_show_hide(login, show, hide) {
	show_hide((get_cookie_username() == login), show, hide);
}

function user_login_show(login, show) {
	if (get_cookie_username() == login) {
		$(show).show();
	}
}

function logged_in_show_hide(show, hide) {
	show_hide(cookie_check_logged_in(), show, hide);
}

function user_login_show_hide_channel_remove(login) {
	if ($('overlay_channels')) {
		var children = $('overlay_channels').immediateDescendants().collect(function(child) {return child.id + '_edit'})
		if (children && children.length > 0) {
			user_login_show_hide(login, children, []);
		}
	}
}

function show_hide(condition, true_ids, false_ids) {
	var show_array = (condition ? true_ids : false_ids) || new Array();
	var hide_array = (condition ? false_ids : true_ids) || new Array();
	show_array.each(function(item) { $(item).show(); });
	hide_array.each(function(item) { $(item).hide(); });
}

function disable(controls) {
	controls.each(function(item) { $(item).disable(); });
}

function enable(controls) {
	controls.each(function(item) { $(item).enable(); });
}

//extend JS String object with trim() method
// Removes leading whitespaces
function LTrim( value ) {var re = /\s*((\S+\s*)*)/;	return value.replace(re, '$1');}
// Removes ending whitespaces
function RTrim( value ) {var re = /((\s*\S+)*)\s*/;return value.replace(re, '$1');}
// Removes leading and ending whitespaces
String.prototype.trim = function trim() {return LTrim(RTrim(this));}

function toggle_current_class(ids, index){
	for (var i=0; i< ids.size(); i++) {
		elem = $(ids[i])
		if (elem) {
			Element.removeClassName(ids[i], 'current')
			if (i == index) {Element.addClassName(ids[i], 'current')}
		}
	}
}

function show_dev_content(string) {
	if ($('dev')) {
		$('dev').innerHTML = string
	}
}

// Roll Over Code -- won't work with IE6/PNG (by design) as they IMG's will be replaced with span's.
var RollOverImg = {
	onRollOver: function(img)
	{
	  var parts = String(img.src).split("/");
		var imgname = parts.pop();
		img.src = parts.join("/") + "/_" + imgname;
	},

	onRollOut: function(img)
	{
	  var parts = String(img.src).split("/");
		var imgname = String(parts.pop()).substring(1);
		img.src = parts.join("/") + "/" + imgname;
	}	
}

/** Not sure if any of these are being used, doesn't seem like it... **/
/** Special in place editor for tags **/
Ajax.InPlaceTagEditor = Class.create();
Ajax.InPlaceTagEditor.defaultHighlightColor = "#FFFF99";
Ajax.InPlaceTagEditor.prototype = {
  initialize: function(element, url, options) {
    this.url = url;
    this.element = $(element);

    this.options = Object.extend({
      paramName: "value",
      okButton: true,
      okText: "ok",
      cancelLink: true,
      cancelText: "cancel",
      savingText: "Saving...",
      clickToEditText: "Click to edit",
      okText: "ok",
      rows: 1,
      onComplete: function(transport, element) {
        new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
      },
      onFailure: function(transport) {
        alert("Error communicating with the server: " + transport.responseText.stripTags());
      },
      callback: function(form) {
        return Form.serialize(form);
      },
      handleLineBreaks: true,
      loadingText: 'Loading...',
      savingClassName: 'inplaceeditor-saving',
      loadingClassName: 'inplaceeditor-loading',
      formClassName: 'inplaceeditor-form',
      highlightcolor: Ajax.InPlaceTagEditor.defaultHighlightColor,
      highlightendcolor: "#FFFFFF",
      externalControl: null,
      submitOnBlur: false,
      ajaxOptions: {},
      evalScripts: false
    }, options || {});

    if(!this.options.formId && this.element.id) {
      this.options.formId = this.element.id + "-inplaceeditor";
      if ($(this.options.formId)) {
        // there's already a form with that name, don't specify an id
        this.options.formId = null;
      }
    }
    
    if (this.options.externalControl) {
      this.options.externalControl = $(this.options.externalControl);
    }
    
    this.originalBackground = Element.getStyle(this.element, 'background-color');
    if (!this.originalBackground) {
      this.originalBackground = "transparent";
    }
    
    this.element.title = this.options.clickToEditText;
    
    this.onclickListener = this.enterEditMode.bindAsEventListener(this);
    this.mouseoverListener = this.enterHover.bindAsEventListener(this);
    this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
    //Event.observe(this.element, 'click', this.onclickListener);
    //Event.observe(this.element, 'mouseover', this.mouseoverListener);
    //Event.observe(this.element, 'mouseout', this.mouseoutListener);
    if (this.options.externalControl) {
      Event.observe(this.options.externalControl, 'click', this.onclickListener);
      //Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
      //Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
    }
  },
  enterEditMode: function(evt) {
    if (this.saving) return;
    if (this.editing) return;
    this.editing = true;
    this.onEnterEditMode();
    if (this.options.externalControl) {
      Element.hide(this.options.externalControl);
    }
    Element.hide(this.element);
    this.createForm();
    this.element.parentNode.insertBefore(this.form, this.element);
    if (!this.options.loadTextURL) Field.scrollFreeActivate(this.editField);
    // stop the event to avoid a page refresh in Safari
    if (evt) {
      Event.stop(evt);
    }
    return false;
  },
  createForm: function() {
    this.form = document.createElement("form");
    this.form.id = this.options.formId;
    Element.addClassName(this.form, this.options.formClassName)
    this.form.onsubmit = this.onSubmit.bind(this);

    this.createEditField();

    if (this.options.textarea) {
      var br = document.createElement("br");
      this.form.appendChild(br);
    }

    if (this.options.okButton) {
      okButton = document.createElement("input");
      okButton.type = "submit";
      okButton.value = this.options.okText;
      okButton.className = 'editor_ok_button';
      this.form.appendChild(okButton);
    }

    if (this.options.cancelLink) {
      cancelLink = document.createElement("a");
      cancelLink.href = "#";
      cancelLink.appendChild(document.createTextNode(this.options.cancelText));
      cancelLink.onclick = this.onclickCancel.bind(this);
      cancelLink.className = 'editor_cancel';      
      this.form.appendChild(cancelLink);
    }
  },
  hasHTMLLineBreaks: function(string) {
    if (!this.options.handleLineBreaks) return false;
    return string.match(/<br/i) || string.match(/<p>/i);
  },
  convertHTMLLineBreaks: function(string) {
    return string.replace(/<br>/gi, "\n").replace(/<br\/>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<p>/gi, "");
  },
  createEditField: function() {
    var text;
    if(this.options.loadTextURL) {
      text = this.options.loadingText;
    } else {
      text = this.getText();
    }

    var obj = this;
    
    if (this.options.rows == 1 && !this.hasHTMLLineBreaks(text)) {
      this.options.textarea = false;
      var textField = document.createElement("input");
      textField.obj = this;
      textField.type = "text";
      textField.name = this.options.paramName;
      textField.value = text;
      textField.style.backgroundColor = this.options.highlightcolor;
      textField.className = 'editor_field';
      var size = this.options.size || this.options.cols || 0;
      if (size != 0) textField.size = size;
      if (this.options.submitOnBlur)
        textField.onblur = this.onSubmit.bind(this);
      this.editField = textField;
    } else {
      this.options.textarea = true;
      var textArea = document.createElement("textarea");
      textArea.obj = this;
      textArea.name = this.options.paramName;
      textArea.value = this.convertHTMLLineBreaks(text);
      textArea.rows = this.options.rows;
      textArea.cols = this.options.cols || 40;
      textArea.className = 'editor_field';      
      if (this.options.submitOnBlur)
        textArea.onblur = this.onSubmit.bind(this);
      this.editField = textArea;
    }
    
    if(this.options.loadTextURL) {
      this.loadExternalText();
    }
    this.form.appendChild(this.editField);
  },
  getText: function() {
    return this.element.innerHTML;
  },
  loadExternalText: function() {
    Element.addClassName(this.form, this.options.loadingClassName);
    this.editField.disabled = true;
    new Ajax.Request(
      this.options.loadTextURL,
      Object.extend({
        asynchronous: true,
        onComplete: this.onLoadedExternalText.bind(this)
      }, this.options.ajaxOptions)
    );
  },
  onLoadedExternalText: function(transport) {
    Element.removeClassName(this.form, this.options.loadingClassName);
    this.editField.disabled = false;
    this.editField.value = transport.responseText.stripTags();
    Field.scrollFreeActivate(this.editField);
  },
  onclickCancel: function() {
    this.onComplete();
    this.leaveEditMode();
    return false;
  },
  onFailure: function(transport) {
    this.options.onFailure(transport);
    if (this.oldInnerHTML) {
      this.element.innerHTML = this.oldInnerHTML;
      this.oldInnerHTML = null;
    }
    return false;
  },
  onSubmit: function() {
    // onLoading resets these so we need to save them away for the Ajax call
    var form = this.form;
    var value = this.editField.value;
    
    // do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
    // which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
    // to be displayed indefinitely
    this.onLoading();
    
    if (this.options.evalScripts) {
      new Ajax.Request(
        this.url, Object.extend({
          parameters: this.options.callback(form, value),
          onComplete: this.onComplete.bind(this),
          onFailure: this.onFailure.bind(this),
          asynchronous:true, 
          evalScripts:true
        }, this.options.ajaxOptions));
    } else  {
      new Ajax.Updater(
        { success: this.element,
          // don't update on failure (this could be an option)
          failure: null }, 
        this.url, Object.extend({
          parameters: this.options.callback(form, value),
          onComplete: this.onComplete.bind(this),
          onFailure: this.onFailure.bind(this)
        }, this.options.ajaxOptions));
    }
    // stop the event to avoid a page refresh in Safari
    if (arguments.length > 1) {
      Event.stop(arguments[0]);
    }
    return false;
  },
  onLoading: function() {
    this.saving = true;
    this.removeForm();
    this.leaveHover();
    this.showSaving();
  },
  showSaving: function() {
    this.oldInnerHTML = this.element.innerHTML;
    this.element.innerHTML = this.options.savingText;
    Element.addClassName(this.element, this.options.savingClassName);
    this.element.style.backgroundColor = this.originalBackground;
    Element.show(this.element);
  },
  removeForm: function() {
    if(this.form) {
      if (this.form.parentNode) Element.remove(this.form);
      this.form = null;
    }
  },
  enterHover: function() {
    if (this.saving) return;
    this.element.style.backgroundColor = this.options.highlightcolor;
    if (this.effect) {
      this.effect.cancel();
    }
    Element.addClassName(this.element, this.options.hoverClassName)
  },
  leaveHover: function() {
    if (this.options.backgroundColor) {
      this.element.style.backgroundColor = this.oldBackground;
    }
    Element.removeClassName(this.element, this.options.hoverClassName)
    if (this.saving) return;
	if (this.effect) {
      this.effect.cancel();
    }
    this.effect = new Effect.Highlight(this.element, {
      startcolor: this.options.highlightcolor,
      endcolor: this.options.highlightendcolor,
      restorecolor: this.originalBackground
    });
  },
  leaveEditMode: function() {
    Element.removeClassName(this.element, this.options.savingClassName);
    this.removeForm();
    this.leaveHover();
    this.element.style.backgroundColor = this.originalBackground;
    Element.show(this.element);
    if (this.options.externalControl) {
      Element.show(this.options.externalControl);
    }
    this.editing = false;
    this.saving = false;
    this.oldInnerHTML = null;
    this.onLeaveEditMode();
  },
  onComplete: function(transport) {
    this.leaveEditMode();
    this.options.onComplete.bind(this)(transport, this.element);
  },
  onEnterEditMode: function() {},
  onLeaveEditMode: function() {},
  dispose: function() {
    if (this.oldInnerHTML) {
      this.element.innerHTML = this.oldInnerHTML;
    }
    this.leaveEditMode();
    //Event.stopObserving(this.element, 'click', this.onclickListener);
    //Event.stopObserving(this.element, 'mouseover', this.mouseoverListener);
    //Event.stopObserving(this.element, 'mouseout', this.mouseoutListener);
    if (this.options.externalControl) {
      Event.stopObserving(this.options.externalControl, 'click', this.onclickListener);
      //Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener);
      //Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener);
    }
  }
};

Ajax.InPlaceCategoryCollectionEditor = Class.create();
Object.extend(Ajax.InPlaceCategoryCollectionEditor.prototype, Ajax.InPlaceTagEditor.prototype);
Object.extend(Ajax.InPlaceCategoryCollectionEditor.prototype, {
  createEditField: function() {
    if (!this.cached_selectTag) {
      var selectTag = document.createElement("select");
      var collection = this.options.collection || [];
      var optionTag;
      collection.each(function(e,i) {
        optionTag = document.createElement("option");
        optionTag.value = (e instanceof Array) ? e[0] : e;
        if((typeof this.options.value == 'undefined') && 
          ((e instanceof Array) ? this.element.innerHTML == e[1] : e == optionTag.value)) optionTag.selected = true;
        if(this.options.value==optionTag.value) optionTag.selected = true;
        optionTag.appendChild(document.createTextNode((e instanceof Array) ? e[1] : e));
        selectTag.appendChild(optionTag);
      }.bind(this));
      this.cached_selectTag = selectTag;
    }

    this.editField = this.cached_selectTag;
    if(this.options.loadTextURL) this.loadExternalText();
    this.form.appendChild(this.editField);
    this.options.callback = function(form, value) {
      return "value=" + encodeURIComponent(value);
    }
  }
});

Ajax.InPlaceChannelCollectionEditor = Class.create();
Object.extend(Ajax.InPlaceChannelCollectionEditor.prototype, Ajax.InPlaceTagEditor.prototype);
Object.extend(Ajax.InPlaceChannelCollectionEditor.prototype, {
  createEditField: function() {
  	this.messageTag = document.createElement("span");
	this.messageTag.innerHTML = (this.loadingText || 'Loading...') + '&nbsp;';
	this.form.appendChild(this.messageTag)
  	var selectTag = document.createElement("select");
	this.editField = selectTag;
	this.editField.style.cssText='display:none'; //ie7 hack
	this.form.appendChild(this.editField);
    this.options.callback = function(form, value, overlay_id) {
      return "value=" + encodeURIComponent(value) + "&id="+encodeURIComponent(overlay_id);
    }
  	//we have to get the list of channels before
	//we can create the edit field baby
    this.loadExternalText();
  },
  onLoadedExternalText: function(transport) {
  	Element.removeClassName(this.form, this.options.loadingClassName);
	var selectTag = this.editField;
	var collection = eval(transport.responseText.stripTags());
    var optionTag;
    collection.each(function(e,i) {
      optionTag = document.createElement("option");
      optionTag.value = (e instanceof Array) ? e[0] : e;
      if((typeof this.options.value == 'undefined') && 
        ((e instanceof Array) ? this.element.innerHTML == e[1] : e == optionTag.value)) optionTag.selected = true;
      if(this.options.value==optionTag.value) optionTag.selected = true;
      optionTag.appendChild(document.createTextNode((e instanceof Array) ? e[1] : e));
      selectTag.appendChild(optionTag);
    }.bind(this));
	
	this.messageTag.style.cssText='display:none;';
	if (this.okButton) {this.okButton.style.cssText='';} 
	this.editField.style.cssText='';
	this.editField.disabled = false;
	Field.scrollFreeActivate(this.editField);
  },
  createForm: function() {
    this.form = document.createElement("form");
    this.form.id = this.options.formId;
    Element.addClassName(this.form, this.options.formClassName)
    this.form.onsubmit = this.onSubmit.bind(this);

    this.createEditField();

    if (this.options.textarea) {
      var br = document.createElement("br");
      this.form.appendChild(br);
    }

    if (this.options.okButton) {
      okButton = document.createElement("input");
      okButton.type = "submit";
      okButton.value = this.options.okText;
	  okButton.style.cssText='display:none'
      okButton.className = 'editor_ok_button';
      this.form.appendChild(okButton);
	  this.okButton = okButton;
    }

    if (this.options.cancelLink) {
      cancelLink = document.createElement("a");
      cancelLink.href = "#";
      cancelLink.appendChild(document.createTextNode(this.options.cancelText));
      cancelLink.onclick = this.onclickCancel.bind(this);
      cancelLink.className = 'editor_cancel';      
      this.form.appendChild(cancelLink);
    }
  },  
  loadExternalText: function() {
    Element.addClassName(this.form, this.options.loadingClassName);
    this.editField.disabled = true;
    new Ajax.Request(
      this.options.loadTextURL,
      Object.extend({
        asynchronous: true,
        onComplete: this.onLoadedExternalText.bind(this)
      }, this.options.ajaxOptions)
    );
  },
  onSubmit: function() {
    // onLoading resets these so we need to save them away for the Ajax call
    var form = this.form;
    var value = this.editField.value;
    
    // do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
    // which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
    // to be displayed indefinitely
    this.onLoading();
    
    if (this.options.evalScripts) {
      new Ajax.Request(
        this.url, Object.extend({
          parameters: this.options.callback(form, value, this.options.overlay_id),
          onComplete: this.onComplete.bind(this),
          onFailure: this.onFailure.bind(this),
          asynchronous:true, 
          evalScripts:true
        }, this.options.ajaxOptions));
    } else  {
      new Ajax.Updater(
        { success: this.element,
          // don't update on failure (this could be an option)
          failure: null }, 
        this.url, Object.extend({
          parameters: this.options.callback(form, value),
          onComplete: this.onComplete.bind(this),
          onFailure: this.onFailure.bind(this)
        }, this.options.ajaxOptions));
    }
    // stop the event to avoid a page refresh in Safari
    if (arguments.length > 1) {
      Event.stop(arguments[0]);
    }
    return false;
  }
});