/*** Prototype extensions ***/

Prototype.Browser.IE6 = (Prototype.Browser.IE &&
  parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf('MSIE')+5),10)==6);
  // Use this only for presentational changes. If you need to change actual
  // behavior, use feature detection, not browser detection.



LowPro = {};
LowPro.Version = '0.5';
LowPro.CompatibleWithPrototype = '1.6';

if (Prototype.Version.indexOf(LowPro.CompatibleWithPrototype) != 0 && window.console && window.console.warn)
  console.warn("This version of Low Pro is tested with Prototype " + LowPro.CompatibleWithPrototype + 
                  " it may not work as expected with this version (" + Prototype.Version + ")");

if (!Element.addMethods) 
  Element.addMethods = function(o) { Object.extend(Element.Methods, o) };

// Simple utility methods for working with the DOM
DOM = {};

// DOMBuilder for prototype
DOM.Builder = {
	tagFunc : function(tag) {
    return function() {
     var attrs, children;
     if (arguments.length>0) {
       if (arguments[0].constructor == Object) {
         attrs = arguments[0];
         children = Array.prototype.slice.call(arguments, 1);
       } else {
         children = arguments;
       };
       children = $A(children).flatten()
     }
     return DOM.Builder.create(tag, attrs, children);
    };
  },
	create : function(tag, attrs, children) {
		attrs = attrs || {}; children = children || []; tag = tag.toLowerCase();
		var el = new Element(tag, attrs);

		for (var i=0; i<children.length; i++) {
			if (typeof children[i] == 'string') 
			  children[i] = document.createTextNode(children[i]);
			el.appendChild(children[i]);
		}
		return $(el);
	}
};

// Automatically create node builders as $tagName.
(function() { 
	var els = ("p|div|span|strong|em|img|table|tr|td|th|thead|tbody|tfoot|pre|code|" + 
				     "h1|h2|h3|h4|h5|h6|ul|ol|li|form|input|textarea|legend|fieldset|" + 
				     "select|option|blockquote|cite|br|hr|dd|dl|dt|address|a|button|abbr|acronym|" +
				     "script|link|style|bdo|ins|del|object|param|col|colgroup|optgroup|caption|" + 
				     "label|dfn|kbd|samp|var").split("|");
  var el, i=0;
	while (el = els[i++]) 
	  window['$' + el] = DOM.Builder.tagFunc(el);
})();

DOM.Builder.fromHTML = function(html) {
  var root;
  if (!(root = arguments.callee._root))
    root = arguments.callee._root = document.createElement('div');
  root.innerHTML = html;
  return root.childNodes[0];
};



// Wraps the 1.6 contentloaded event for backwards compatibility
//
// Usage:
//
// Event.onReady(callbackFunction);
Object.extend(Event, {
  onReady : function(f) {
    if (document.body) f();
    else document.observe('dom:loaded', f);
  }
});

// Based on event:Selectors by Justin Palmer
// http://encytemedia.com/event-selectors/
//
// Usage:
//
// Event.addBehavior({
//      "selector:event" : function(event) { /* event handler.  this refers to the element. */ },
//      "selector" : function() { /* runs function on dom ready.  this refers to the element. */ }
//      ...
// });
//
// Multiple calls will add to exisiting rules.  Event.addBehavior.reassignAfterAjax and
// Event.addBehavior.autoTrigger can be adjusted to needs.
Event.addBehavior = function(rules) {
  var ab = this.addBehavior;
  Object.extend(ab.rules, rules);

  if (!ab.responderApplied) {
    Ajax.Responders.register({
      onComplete : function() { 
        if (Event.addBehavior.reassignAfterAjax) 
          setTimeout(function() { ab.reload() }, 10);
      }
    });
    ab.responderApplied = true;
  }

  if (ab.autoTrigger) {
    this.onReady(ab.load.bind(ab, rules));
  }

};

Event.delegate = function(rules) {
  return function(e) {
      var element = $(e.element());
      for (var selector in rules)
        if (element.match(selector)) return rules[selector].apply(this, $A(arguments));
    }
}

Object.extend(Event.addBehavior, {
  rules : {}, cache : [],
  reassignAfterAjax : false,
  autoTrigger : true,

  load : function(rules) {
    for (var selector in rules) {
      var observer = rules[selector];
      var sels = selector.split(',');
      sels.each(function(sel) {
        var parts = sel.split(/:(?=[a-z]+$)/), css = parts[0], event = parts[1];
        $$(css).each(function(element) {
          if (event) {
            var wrappedObserver = Event.addBehavior._wrapObserver(observer);
            $(element).observe(event, wrappedObserver);
            Event.addBehavior.cache.push([element, event, wrappedObserver]);
          } else {
            if (!element.$$assigned || !element.$$assigned.include(observer)) {
              if (observer.attach) observer.attach(element);

              else observer.call($(element));
              element.$$assigned = element.$$assigned || [];
              element.$$assigned.push(observer);
            }
          }
        });
      });
    }
  },

  unload : function() {
    this.cache.each(function(c) {
      Event.stopObserving.apply(Event, c);
    });
    this.cache = [];
  },

  reload: function() {
    var ab = Event.addBehavior;
    ab.unload(); 
    ab.load(ab.rules);
  },

  _wrapObserver: function(observer) {
    return function(event) {
      if (observer.call(this, event) === false) event.stop(); 
    }
  }

});

Event.observe(window, 'unload', Event.addBehavior.unload.bind(Event.addBehavior));

// A silly Prototype style shortcut for the reckless
$$$ = Event.addBehavior.bind(Event);

// Behaviors can be bound to elements to provide an object orientated way of controlling elements
// and their behavior.  Use Behavior.create() to make a new behavior class then use attach() to
// glue it to an element.  Each element then gets it's own instance of the behavior and any
// methods called onxxx are bound to the relevent event.
// 
// Usage:
// 
// var MyBehavior = Behavior.create({
//   onmouseover : function() { this.element.addClassName('bong') } 
// });
//
// Event.addBehavior({ 'a.rollover' : MyBehavior });
// 
// If you need to pass additional values to initialize use:
//
// Event.addBehavior({ 'a.rollover' : MyBehavior(10, { thing : 15 }) })
//
// You can also use the attach() method.  If you specify extra arguments to attach they get passed to initialize.
//
// MyBehavior.attach(el, values, to, init);
//
// Finally, the rawest method is using the new constructor normally:
// var draggable = new Draggable(element, init, vals);
//
// Each behaviour has a collection of all its instances in Behavior.instances
//
var Behavior = {
  create: function() {
    var parent = null, properties = $A(arguments);
    if (Object.isFunction(properties[0]))
      parent = properties.shift();

      var behavior = function() { 
        if (!this.initialize) {
          var args = $A(arguments);

          return function() {
            var initArgs = [this].concat(args);
            behavior.attach.apply(behavior, initArgs);
          };
        } else {
          var args = (arguments.length == 2 && arguments[1] instanceof Array) ? 
                      arguments[1] : Array.prototype.slice.call(arguments, 1);

          this.element = $(arguments[0]);
          this.initialize.apply(this, args);
          behavior._bindEvents(this);
          behavior.instances.push(this);
        }
      };

    Object.extend(behavior, Class.Methods);
    Object.extend(behavior, Behavior.Methods);
    behavior.superclass = parent;
    behavior.subclasses = [];
    behavior.instances = [];

    if (parent) {
      var subclass = function() { };
      subclass.prototype = parent.prototype;
      behavior.prototype = new subclass;
      parent.subclasses.push(behavior);
    }

    for (var i = 0; i < properties.length; i++)
      behavior.addMethods(properties[i]);

    if (!behavior.prototype.initialize)
      behavior.prototype.initialize = Prototype.emptyFunction;

    behavior.prototype.constructor = behavior;

    return behavior;
  },
  Methods : {
    attach : function(element) {
      return new this(element, Array.prototype.slice.call(arguments, 1));
    },
    _bindEvents : function(bound) {
      for (var member in bound) {
        var matches = member.match(/^on(.+)/);
        if (matches && typeof bound[member] == 'function')
          bound.element.observe(matches[1], Event.addBehavior._wrapObserver(bound[member].bindAsEventListener(bound)));
      }
    }
  }
};



Remote = Behavior.create({
  initialize: function(options) {
    if (this.element.nodeName == 'FORM') new Remote.Form(this.element, options);
    else new Remote.Link(this.element, options);
  }
});

Remote.Base = {
  initialize : function(options) {
    this.options = Object.extend({
      evaluateScripts : true
    }, options || {});

    this._bindCallbacks();
  },
  _makeRequest : function(options) {
    if (options.update) new Ajax.Updater(options.update, options.url, options);
    else new Ajax.Request(options.url, options);
    return false;
  },
  _bindCallbacks: function() {
    $w('onCreate onComplete onException onFailure onInteractive onLoading onLoaded onSuccess').each(function(cb) {
      if (Object.isFunction(this.options[cb]))
        this.options[cb] = this.options[cb].bind(this);
    }.bind(this));
  }
}

Remote.Link = Behavior.create(Remote.Base, {
  onclick : function() {
    var options = Object.extend({ url : this.element.href, method : 'get' }, this.options);
    return this._makeRequest(options);
  }
});


Remote.Form = Behavior.create(Remote.Base, {
  onclick : function(e) {
    var sourceElement = e.element();

    if (['input', 'button'].include(sourceElement.nodeName.toLowerCase()) && 
        sourceElement.type == 'submit')
      this._submitButton = sourceElement;
  },
  onsubmit : function() {
    var options = Object.extend({
      url : this.element.action,
      method : this.element.method || 'get',
      parameters : this.element.serialize({ submit: this._submitButton.name })
    }, this.options);
    this._submitButton = null;
    return this._makeRequest(options);
  }
});

Observed = Behavior.create({
  initialize : function(callback, options) {
    this.callback = callback.bind(this);
    this.options = options || {};
    this.observer = (this.element.nodeName == 'FORM') ? this._observeForm() : this._observeField();
  },
  stop: function() {
    this.observer.stop();
  },
  _observeForm: function() {
    return (this.options.frequency) ? new Form.Observer(this.element, this.options.frequency, this.callback) :
                                      new Form.EventObserver(this.element, this.callback);
  },
  _observeField: function() {
    return (this.options.frequency) ? new Form.Element.Observer(this.element, this.options.frequency, this.callback) :
                                      new Form.Element.EventObserver(this.element, this.callback);
  }
});



/* helper method for stripping chars from string */
String.prototype.strip = function( exp ){ return this.replace(exp?exp:/\s/g,""); };

// defining false resend for use on page
var resend = false

/*Behavioral class for inviting friends */
FriendsInvite = Behavior.create({
  initialize: function() {
    this.counter = 0;
    this.id = 0;
    this.form = 'invite_form';
    if(resend) 
    {
      this.resend(resend.email, resend.id);
    }
  },

  onclick: function(e) {
		var source = Event.element(e);
		Event.stop(e);
    if($(source).hasClassName('add_contact')) return this.addContact();
    if($(source).hasClassName('remove_contact')) return this.removeContact($(source));
		if($(source).id == 'send_submit') return this.checkNonZero();
  },
  onkeyup: function(e) {
    var source = Event.element(e);
    Event.stop(e);
		if($(source).id == 'invitation_message') return this.previewMessage();
  },

  addContact: function() {
    contacts = $F('add_friend_mail').strip().split(",")
    var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  
    //setting this to avoid "this" problems inside each
    var _this = this 
    contacts.each(
      function(contact) 
      {
        if (_this.exists(contact)) {
          new Effect.Highlight('contact_'+contact, {startcolor:'#dd1111', endcolor:'#dff3fd'});
        }
        else if(filter.test(contact) ) {
          _this.createContact(contact, contact);
        }
        else {
          _this.displayAlert('#invitation_send_alert');
        }
      }
    )
  },

  exists : function(value){
    if($('contact_'+value))
     	return true;
    else
      return false;
  },
	
  removeContact : function(el){
    Effect.Fade(el.parentNode.parentNode, {duration: 0.5, afterFinish: function(){el.parentNode.parentNode.remove();}});
    this.updateCounter(-1);
  },
	createContact : function(value, name, resend){
    listEl = document.createElement('li');
    listEl.id = 'contact_'+value;
    contact = name+' <a href="#"><img class="remove_contact" src="/images/buttons/delete.gif" alt="delete icon" /></a>';

    if (resend) {
      contact += '<input type="hidden" name="invitation[recipents]['+this.id+'][resend_id]" value="'+resend+'"';
    } else {
      contact += '<input type="hidden" name="invitation[recipents]['+this.id+'][email]" value="'+value+'" />';
    }

    Element.update(listEl,contact);

    $('invitation_list_contacts').appendChild(listEl);
		new Effect.Highlight(listEl, {startcolor:'#fff72a', endcolor:'#dff3fd'});
    $('add_friend_mail').value = ''
    this.updateCounter(+1);
    this.id ++;
  },
	displayAlert : function(el_query){ 
    al = $$(el_query)[0];
    al.show();
  	Effect.Fade($$(el_query)[0],{from: 1.0,delay: 2.0});
  },
  checkNonZero : function(){
    if (this.counter == 0){
      this.displayAlert('#no_recipents_alert');
      return false;
    }
		else{
      $(this.form).submit();	
		}
  },
	updateCounter : function(value){
    this.counter += value;
    form = 'people'
    if (this.counter == 1)
      form = 'person';
    $('recipents_counter').innerHTML = this.counter+' '+form;
  },
  previewMessage: function(){
    $('preview_message').innerHTML = $F('invitation_message');
  },
  resend :function(email, id) {
    this.createContact(email,email, id);
  }

});

Event.addBehavior({
	'#invite_form': FriendsInvite()
});

/*Behavioral class for inviting friends */
BulkUploadForm = Behavior.create({
  initialize: function() {
    this.counter = 1;
    
    if(this.form=$('bulk_upload_form')){
      var firstFileInput=this.form.down('input[name="batch[files][0]"]'),
          addAnother=$('add_another_file');
      if(firstFileInput){
        firstFileInput.observe('click',function(ev){
          addAnother.show();
            // Hidden by default until first file is entered. This is not yet
            // foolproof, as the link remains visible if the first file input
            // is left empty, or if the first file input is changed and then
            // removed. The "onchange" event is not reliable across browsers
            // for input[type=file].
        });
      }
    }
  },

  onclick: function(e) {
		var source = Event.element(e);
    if($(source).parentNode.className == 'remove_file')
      {
       Event.stop(e);
       return this.removeFile($(source));
      }
    if($(source).id == 'add_another_file')
      {
       Event.stop(e);
       return this.addFile();
      }
  },

  removeFile: function(trigger)
  {
    if ($('bulk_upload_form').getElementsByTagName('fieldset').length == 1)
    {
      alert('You need at least one file to upload.');
    }
    else
    {
      trigger.parentNode.parentNode.parentNode.removeChild(trigger.parentNode.parentNode);
    }
  },

  addFile: function()
  {
    fs = $('bulk_upload_form').getElementsByTagName('fieldset');
    last_one = fs[fs.length-1];
    new Insertion.After(last_one, '<fieldset id="bulk_fieldset_'+this.counter+'"> <input type="file" name="batch[files]['+this.counter+']"/><a href="#" class="remove_file"> <img src="/images/buttons/delete-file.gif" alt="remove" /></a></fieldset>');
    this.counter++;
  }

  });
Event.addBehavior({
	'#bulk_files': BulkUploadForm
});

/* Behavioral class for selecting flickr photos */

PhotoSelector = Behavior.create({
  initialize: function() {
    this.counter = 0;
    this.i = 0;
    this.current_page = 1;
  },

  onclick: function(e) {
		var source = Event.element(e);
      if ($(source).className == 'flickr')
      {
       Event.stop(e);
       return this.choose(source);
      }
      if ($(source).hasClassName('sliderPrev'))
      {
       Event.stop(e);
       return this.previous_next(-1);
      }
      if ($(source).hasClassName('sliderNext'))
      {
       Event.stop(e);
       return this.previous_next(1);
      }
      if ($(source).parentNode.parentNode.className == 'pagination')
      {
        Event.stop(e);
        return this.switch_to_page(source);
      }

      if($(source).className == 'import_all')
      {
        $('importing').show();
        $('selection_wrap').hide();
        return true;
      }
  },
  
  onsubmit: function(e) {
		var source = Event.element(e);
    if($(source).id == 'submit_form')
    {
      $('importing').show();
      $('selection_wrap').hide();
      return true;
    }
  },
  
  choose: function(image) {
    if(image.parentNode.parentNode.className == 'selected') {
      this.remove_from_selected(image);
    } else {
      this.add_to_selected(image);
    }
  },
  remove_from_selected: function(image)
  {
    image.parentNode.parentNode.className = ''
    this.i--;
    $('selected_count').innerHTML = this.i;
    if (i = $(image.id+'_input'))
    {
      i.remove();
    }
  },
  add_to_selected: function (image)
  {
    image.parentNode.parentNode.className = 'selected';
    this.i++;
    $('selected_count').innerHTML = this.i;
    new Insertion.Bottom('submit_form','<input type="hidden" name="images[]" id = "'+image.id+'_input" value="'+image.id.split('_')[1]+'" />');
  },
  previous_next: function(dir)
  {
    switcher = $('switch-page_'+(this.current_page*1+dir));
    if(switcher)
    {
      return this.switch_to_page(switcher);
    }
    return false;
  },
  switch_to_page: function (switcher)
  {
    page = switcher.id.split('-')[1];
    cur_page_no = page.split('_')[1];
    $$('.page_selector').each( function(p) {
      p_no = p.getElementsByTagName('a')[0].id.split('_')[1];
      if((p_no - cur_page_no)>5 || (cur_page_no - p_no)>5)
      {
        p.hide();
      } else {
        p.show();
      }
    });
    (cur_page_no > 6) ? $('first_hellip').show():$('first_hellip').hide();
    ($$('.page_selector').length - cur_page_no > 5) ? $('last_hellip').show():$('last_hellip').hide();

    $$('.page_selector.current')[0].removeClassName('current');
    switcher.parentNode.addClassName('current');
    if($(page))
    {
      $$('#page_wrapper>div.selected').each( function(p) {
        p.removeClassName('selected');
      });
      $(page).addClassName('selected');
    } else {
      // get this page with ajax
      new Ajax.Request(switcher.href, {asynchronous:true, evalScripts:true, onComplete: function() {
        $$('#page_wrapper>div.selected').each( function(p) {
          p.removeClassName('selected');
        });
        $(page).addClassName('selected');
      }});
    }
    this.current_page = page.split('_')[1];
  }
});
Event.addBehavior({
	'#flickr': PhotoSelector
});

document.observe('dom:loaded', function(event) {
  var share_list = $('share_list_contacts');
  var share_form = $('share_form');
  if (!share_list) return false;
  
  $$('.add-friend-button').each(function(input) {
    var contact_adder = new Adder(input, share_list, $('recipents_counter'));
  });
  
  $$('.separate-add-friend-button').each(function(cntrl) {
    var contact_adder = new SeparateFieldAdder(cntrl, $('share_contact'), share_list, $('recipents_counter'));
  });
  
  share_form.observe('submit', function(event) {
    if (share_list.select('li').size() == 0) {
      event.stop();
      
      share_form.select('input.send_submit').each(function(button) {
        button.up().insert({
          before: p_alert()
        })
      });
    };
    function p_alert() {
      return new Element('p', {
        'class' : 'alert'
      }).update('Please select at least one friend to share with.');
    }
  });
});

/*Behavioral class for sharing photo/videos */
Adder = Class.create({
  initialize: function(input, share_list, counter) {
    this.input = input;
    this.share_list = share_list;
    this.counter = counter || null;
    
    this.contact = new Contact($F(this.input));
    var id_template = new Template('contact_#{t}#{v}');
    this.id = id_template.evaluate({ t: this.contact.type, v: this.contact.value });
    
    this.input.observe('click', this.create.bindAsEventListener(this));
  },
  create: function(event) {
    event.stop();
    if ($(this.id)) { return false; }
    
    var li = this.li();
    this.share_list.insert({bottom: li});
    li.highlight({startcolor:'#fff72a', endcolor:'#dff3fd'});
    this.updateCounter();
  },
  count: function() {
    return this.share_list.select('li').size();
  },
  destroy: function(event) {
    event.stop();
    event.element().up('li').remove();
    this.updateCounter();
  },
  li: function() {
    return new Element('li', {
      'id' : this.id
    }).update(this.input.readAttribute('title'))
      .insert({bottom: this.delete_button_link() })
      .insert({bottom: this.recipients_input() });
  },
  delete_button_image: function() {
    return new Element('img', {
      'src' : '/images/buttons/delete.gif',
      'class' : 'removeContact',
      'alt' : 'delete icon'
    });
  },
  delete_button_link: function() {
    return new Element('a', {
      'href' : '#',
      'class' : 'removeContact'
    }).insert(this.delete_button_image())
      .observe('click', this.destroy.bindAsEventListener(this));
  },
  recipients_input: function() {
    var name_template = new Template('share[recipients][#{i}][#{t}]');
    return new Element('input', {
      'type' : 'hidden',
      'name' : name_template.evaluate({i: (this.count() + 1), t: this.contact.type }),
      'value' : this.contact.value
    });
  },
  updateCounter:function() {
    if (!this.counter) return false;
    this.counter.update(this.count() + (this.count() == 1 ? ' person' : ' people'));
  }
});

SeparateFieldAdder = Class.create(Adder, {
  initialize: function(cntrl, input, share_list, counter) {
    this.cntrl = cntrl;
    this.input = input;
    this.share_list = share_list;
    this.counter = counter || null;
    
    this.cntrl.observe('click', this.create.bindAsEventListener(this));
  },
  create: function(event) {
    event.stop();
    
    this.contact = new Contact($F(this.input));
    if (!this.contact.valid) {
      return false
    }
    var id_template = new Template('contact_#{t}#{v}');
    this.id = id_template.evaluate({ t: this.contact.type, v: this.contact.value });
    if ($(this.id)) { return false; }
    
    var li = this.li();
    this.share_list.insert({bottom: li});
    li.highlight({startcolor:'#fff72a', endcolor:'#dff3fd'});
    this.updateCounter();
  },
  li: function() {
    return new Element('li', {
      'id' : this.id
    }).update(this.contact.value)
      .insert({bottom: this.delete_button_link() })
      .insert({bottom: this.recipients_input() });
  }
});

Contact = Class.create();
    
Contact.prototype = {
    initialize: function(value) {
      this.valid = false;
      this.value = value;
      if(this.checkMail()){
        this.valid = true;
        this.type = 'mail';
      }
      else if (this.checkFriendMail()){
        this.valid = true;
        this.type = 'friend_mail';
      }
      else if (this.checkFriendPhone()){
        this.valid = true;
        this.type = 'friend_phone';
      }
      else if (this.checkPhone()){
        this.valid = true;
        this.type = 'phone';
      }
      else{
        alert('Please provide valid US phone number (without leading `1`) or email');
        return false;
      }
    },

    isValid: function(){
      return false;
    },
    checkMail: function(){
      var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
      return filter.test(this.value)
    },

    checkPhone: function(){
      if(this.value.replace(/[^\d]/g,"").match(/^\d{10}$/)){
        this.value = this.value.replace(/[^\d]/g,"");
        return true;
      }
      return false
    },
    checkFriendPhone: function(){
      if ((this.value.split("_")[0] == 'phone') && (this.value.split("_")[1].match(/^\d{1,10}$/))){
        this.value = this.value.split("_")[1];
        return true;
      } 
      return false;
    },
    checkFriendMail: function(){
      if( (this.value.split("_")[0] == 'mail') && (this.value.split("_")[1].match(/^\d{1,10}$/))){
        this.value = this.value.split("_")[1];
        return true;
      } 
      return false;
    }
}

function checkEmptyComment(){
  if ($F('annotation_comment') == ''){
      commentError('Please write a message before posting your comment.');
      return false;
  }
}

function commentError(message){
  $('comment_error').innerHTML = message
  $('comment_error').show();
  Effect.Fade($('comment_error'),{from: 1.0,delay: 2.0});
}

function toggle_lightbox(){
  if ($('lightbox')){
    Element.remove('lightbox');
    Element.remove('overlay');
  }
}

/*Extends inplace editor with some custom Features */
Ajax.InPlaceEditorOrig = Class.create();
Ajax.InPlaceEditorOrig.prototype = Ajax.InPlaceEditor.prototype
Ajax.InPlaceEditor.defaultHighlightColor = "#FFFF00";
Ajax.InPlaceEditor.prototype = {
  initialize: function(element, url, options) {
    this.url = url;
    this.element = $(element);

    this.options = Object.extend({
      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.InPlaceEditor.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) {
      var el = new Element('a', { 'href' : '#', 'id' : this.options.externalControl }).setStyle({'cursor' : 'pointer'});
      el.innerHTML = this.options.clickToEditText;
      this.element.insert({ 'after' : el });
    }
   
    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);
//this bit change to allow only the external control to be clicked
    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);
    } else {
      Event.observe(this.element, 'click', this.onclickListener);
      Event.observe(this.element, 'mouseover', this.mouseoverListener);
      Event.observe(this.element, '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);
//added next line to keep the form inline
        this.form.style.display = 'inline';
    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);
    }

            extraText = document.createElement("span");
            extraText.innerHTML = "or ";
            this.form.appendChild(extraText);
 
    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 = "value";
      textField.value = text;
//sets background as white if using externalControl
      if(this.options.externalControl){
        textField.style.backgroundColor = '#FFF';
      } else {
        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 = "value";
      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 = $F(this.editField);
   
    // 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;
// remove hightlight on hover if externalControl
    if(!this.options.externalControl){
   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.options.externalControl){
    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();
//remove effect if externalControl
  if(!this.options.externalControl){
   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);
    }
  }
};

//Add cookie support to prototype

var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};

function show_dashboard(){
	Effect.Appear('dashboard_nav');
	Element.removeClassName('dashboard_nav', 'iefix');
	$('dashboard_open').hide();
	$('dashboard_close').show();
	Cookie.erase('tp-dashboard-pref');
	return false;
}

function hide_dashboard(){
	Effect.Fade('dashboard_nav');
	Element.removeClassName('dashboard_nav', 'iefix');
	$('dashboard_open').show();
	$('dashboard_close').hide();
	Cookie.set('tp-dashboard-pref', '1');
	return false;
}

//Show dashboard if its on page and you have left it open
Event.onReady(function(){
	var display_dashboard = Cookie.get('tp-dashboard-pref');
	var dashboard = $('dashboard_nav');
	if(dashboard){
		$('dashboard_nav').style.display = !display_dashboard ? 'inline' : 'none';
		$('dashboard_close').style.display = !display_dashboard ? 'block' : 'none';
		$('dashboard_open').style.display = !display_dashboard ? 'none' : 'block';
	}
});

Event.addBehavior({
	'a.closeLb:click' : function(e){
	toggle_lightbox();
	return false;
	},
	'a.closeLbCookie:click' : function(e){
		Cookie.erase('CommunitySignedInCookie');
		toggle_lightbox();
	}
});

Event.addBehavior({
  'a.toggle_tag:click' : function(e){
  $('tag-editor-link').toggle();
  $('tag-editor').toggle();
  return false;
  }
});

Event.addBehavior({
  'li.media li.tags span.open:mouseover' : function(e){
    new Effect.Appear(document.getElementsByClassName('full_tags',this.parentNode)[0],{duration:0.2});
  },
  'li.media li.tags div.full_tags:mouseout' : function(e){
      var relTarg = e.relatedTarget || e.toElement;
      if(relTarg.parentNode != this && relTarg != this)
      {
        this.style.display = 'none';
      }
  } 
});

Event.addBehavior({
 '.default_filled:focus': function(){
  	if (this.value == this.title){
    	this.value = '';
  	}
	}
});
CommentMore = Behavior.create ({
  onclick:  function(e){
    Element.show(document.getElementsByClassName('comment_less', this.element.parentNode)[0].parentNode);
    this.element.hide();
    return false;
  }
});

CommentLess = Behavior.create({
  onclick: function(e){
    Element.show(document.getElementsByClassName('comment_more', this.element.parentNode.parentNode)[0]);
    this.element.parentNode.hide();
    return false;
  }
});

Event.addBehavior({
  'a.comment_more':  CommentMore,
  'a.comment_less': CommentLess
});

DashBoard = Behavior.create({
	initialize : function(){
		this.user = Cookie.get('TpUserDb');
		if(this.user){
			this.user = this.user.evalJSON();
			this.setInfo();
			this.showDashBoard();
			this.hideCTA();
		}
		else{
			this.showCTA();
		}
	},
	setInfo : function(){
		this.setLink('db_welcome', '/users/' + this.user.id + '/edit', this.user.nickname);
		this.setHref('#edit_path', '/users/' + this.user.id + '/edit');
		this.setHref('#invite_path', '/users/' + this.user.id + '/invitations/new');
		this.setHref('#friendships_path', '/users/' + this.user.id + '/friendships');
		this.setHref('#friendrequests_path', '/users/' + this.user.id + '/friend_requests');
		this.setHref('#media_path', '/users/' + this.user.id + '/media');
		this.setHref('#comments_path', '/users/' + this.user.id + '/annotations');
		this.setHref('#favorites_path', '/users/' + this.user.id + '/media/favorites');
		this.setHref('#new_media_path', '/users/' + this.user.id + '/media/new');
		this.setHref('#user_settings_path', '/users/' + this.user.id + '/settings');
		this.setImage('db_user_photo', this.user.avatar_path)
		$$('#friends_count').invoke('update', this.user.friends_count.to_s);
		$$('#friendrequests_count').invoke('update', this.user.friend_requests_count.to_s);
		$$('#media_count').invoke('update', this.user.media_count.to_s);
		$$('#comments_count').invoke('update', this.user.comments_count.to_s);
		$$('#favourites_count').invoke('update', this.user.favorites_count.to_s);
	},
	showDashBoard : function(){
		Effect.Appear('dashboard');
	},
	hideCTA : function(){
		$$('#welcome').invoke('hide');
	},
	showCTA : function(){
	  if ($('welcome')) {
	    Effect.Appear('welcome');
	  };
	},
	setHref : function(el, href){
		var href = href;
		var el = $$(el);
		el.each(function(e){
			e.href = href;
		});
	},
	setLink : function(el, href, link){
		var el = $(el);
		if (el) {
		  el.href = href;
  		el.innerHTML  = link;
		};
	},
	setImage : function(el, src){
		var el = $(el);
		if (el)
		  el.src = src;
	}
});

Event.addBehavior({
	'#dashboard' : DashBoard()
});

Event.addBehavior({
	'a.remote' : Remote.Link
});

var forceMax = Behavior.create({
	initialize: function(max){
		this.maxlength = max;
	},
	onkeyup: function(){
		this.checkLength();
	},
	onkeydown: function(){
		this.checkLength();
	},
	checkLength: function(){
		if(this.element.value.length > this.maxlength){
			this.element.value = this.element.value.substring(0, this.maxlength);
		}
	}
});

Event.addBehavior({
	'input.force_max' : forceMax(this.maxLength)
})

Event.addBehavior({
	'#share_sms_mes' : forceMax(100)
})

function contestEntryPhotoSelect(id)
{
  $$('#old_photos_for_contest>ol>li.selected').each(function(li) { li.removeClassName('selected')});
  $('old_image_'+id).parentNode.addClassName('selected');
  $('selected_photo_id').value = id;
}

/* prototype fix for IE7 unload problem */


Object.extend(Event, {
  unloadCache: function() {
     if (!Event.observers) return;
     for (var i = 0, length = Event.observers.length; i < length; i++) {
       if (Event.observers[i]) {
         Event.stopObserving.apply(this, Event.observers[i]);
         if (Event.observers[i]) {
           Event.observers[i][0] = null;
         }
       }
     }
     Event.observers = false;
   }
});

Event.observe(window, 'load', function() { 
	$A(document.getElementsByClassName('fadeout')).each(function(o) {
		o.opacity = 100.0
		Effect.Fade(o, {duration: 4.0})
	});
});

Event.observe(window, 'load', function() {
	if ($$('input[type="file"]').length > 0 && Prototype.Browser.WebKit) {
		$$('input[type="file"]').invoke('setStyle', {
			background: 'transparent',
			border: '0'			
		});
	}
});

var ResendVerification = Behavior.create({
  onclick: function(event) {
    Event.stop(event);

    var url = this.element.readAttribute('href');
    
    new Ajax.Request(url, {
      method: 'post',
      onFailure: function() {
        alert("Failure.");
      },
      onSuccess:function(xhr) {
        if ($$('div.notice').length == 0) {
          $('resend-verification-control').up('p').insert({before: "<div class='notice'>We have resent your verification.</div>"});
        };
        setTimeout(function() {
          $$('div.notice').invoke('remove');
        }, 2000);
      }.bind(this)
    });
  }
});

var InlineDropdown = Behavior.create({
  initialize: function(block, close_text) {
    this.block = $(block);
  },
  onclick: function(event) {
    Event.stop(event);
    Effect.toggle(this.block, 'blind', { 'duration' : 0.25 });
  }
});

var SigninForm = Behavior.create({
	initialize: function(ajaxFunc, errClass, condition) {
		this.ajaxFunc = ajaxFunc;
		this.errClass  = errClass  || 'error';
		this.condition = condition || true;
		this.errorMessage  = new Template("<li class='" + this.errClass + "'>#{message}</li>");
	},
	onsubmit: function(event) {
		this.clearErrors();
		if (this.emptyInputs().any()) {
			Event.stop(event);
			this.showError("Please provide an email and password.");
		} else {
			Event.stop(event);
			new Ajax.Request('/sessions/' + this.ajaxFunc, {
				method: 'post',
				parameters: this.element.serialize(true),
				onFailure: function(xhr) {
					this.showError("The email and password provided do not match. Please try again.");
				}.bind(this),
				onSuccess: function(xhr) {
					this.element.submit();
				}.bind(this)
			});
		}
	},
	showError: function(message) {
		new Insertion.Bottom(this.element.down('ul'), this.errorMessage.evaluate({ "message" : message }));
	},
	clearErrors: function() {
		this.element.getElementsBySelector('li.'+this.errClass).invoke('remove');
	},
	emptyInputs: function() {
		return this.element.getInputs('text').select(function(input) {
			return !input.present() && this.condition;
		}.bind(this));
	}
});

var DefaultPrefixTextField = Class.create();
DefaultPrefixTextField.prototype = {
  initialize:function(input,value){
    this.input=input;
    this.value=value;
    if (this.shouldReset()) {this.reset();};
    this.input.observe('focus',this.onfocus.bindAsEventListener(this));
    this.input.observe('blur',this.onblur.bindAsEventListener(this));
    this.input.observe('keypress', this.onkeypress.bindAsEventListener(this));
    if (Prototype.Browser.IE) {
      this.input.observe('keydown', this.onkeypress.bindAsEventListener(this));
    }
    this.input.observe('click', this.onfocus.bindAsEventListener(this));
  },
  reset:function(){
    this.input.setStyle({color:'#aaaaaa'}).value=this.value;
  },
  onfocus:function(){
    if($F(this.input)==this.value){
      this.input.setStyle({color:'#000000'});
      this.input.focus();
      this.adjustCursorPosition();
    }
  },
  onblur:function(){
    if(this.shouldReset()) {
      this.reset();
    }
  },
  onkeypress: function(event) {
    if (event.keyCode == 8 && $F(this.input) == this.value) {
      Event.stop(event);
    };
    this.adjustCursorPosition();
  },
  shouldReset: function() {
    return $F(this.input).blank() || 
           $F(this.input) == this.value ||
          !$F(this.input).include(this.value);
  },
  adjustCursorPosition: function() {
    if (document.selection) {
      var r = this.input.createTextRange();
      if (r.text.length == this.value.length) {
        r.moveStart('character', this.value.length);
        r.select();
      };
    } else {
      if (this.input.selectionStart < this.value.length) {
        this.input.selectionStart = this.value.length;
      };
    }
  }
};

Event.observe(window, 'load', function(event){
  [ 'creator-url-0', 'creator-url-1', 'creator-url-2' ].each(function(id) {
    if (!$(id)) return;
    new DefaultPrefixTextField($(id), 'http://');
  }.bind(this));
});

ChooseFrame = Behavior.create({
   onclick: function(ev){
     ev.stop();
     this.element.up('ul').select('li').each(function(el) {
       el.removeClassName('selected');
     });
     this.element.up('li').addClassName('selected');
     frame_id = this.element.id.split("_")[1];
     value_field = this.element.up('fieldset').select("input.selected_frame_id").first();
     value_field.setValue(frame_id);
     return false;
   }
});

Event.addBehavior({
 'a.frame-to-select' : ChooseFrame
})

var FormValidation = Class.create({
  initialize: function(el, func, errClass, errMessageClass, errPlaceHolderID) {
    this._errs = [];
    this.element = $(el) || false;
    if (!this.element) return false;
    
    this.func = func || false;
    this.errClass = errClass || 'error';
    this.errMessageClass = errMessageClass || 'errorExplanation';
    this.errPlaceHolderID = errPlaceHolderID || 'errPlaceHolder';
    this.listen();
  },
  listen: function() {
    this.element.observe('validation:addError', function(event) {
      this._errs.push(event.memo);
    }.bind(this));
    this.element.observe('submit', this.submit.bindAsEventListener(this));
  },
  submit: function(event) {
    this.resetErrs();
    this.element.select('input', 'select', 'textarea').invoke('fire', 'validation:started');
    if (this._errs.length > 0) {
      event.stop();
      this.showErrs();
    } else {
      if (this.func) {
        this.func(this.element);
      };
    };
  },
  showErrs: function() {
    var errDiv = new Element('div', { 'class' : this.errMessageClass });
    var errList = new Element('ul');
    $(this.errPlaceHolderID).replace(errDiv.insert({top: errList}));
    this._errs.each(function(pair) {
      $(pair.get('id')).fire('validation:completed');
      $(pair.get('id')).addClassName(this.errClass);
      errList.insert({bottom: new Element('li').update(pair.get('err'))});
    }.bind(this));
  },
  resetErrs: function() {
    this._errs = [];
    $$('.' + this.errClass).invoke('removeClassName', this.errClass);
    $$('.' + this.errMessageClass).invoke('replace', new Element('div', { 
      'id' : this.errPlaceHolderID 
    }));
  }
});

var InputValidation = Behavior.create({
  initialize: function(conditions) {
    this.conditions = conditions;
    this.form = this.element.up('form');
    this.element.observe('validation:started', this.validate.bindAsEventListener(this));
  },
  validate: function() {
    this.conditions.each(function(pair) {
      if (!pair.get('condition')(this.element, pair.get('additionalParams'))) {
        this.form.fire('validation:addError', $H({
          id  : this.element.readAttribute('id'),
          err : pair.get('message')
        }));
      };
    }.bind(this));
  }
});

var DefaultValueTextField=Class.create({
  // Uses the Prototype JS framework.
  // For generating text input fields that are pre-filled with default values,
  // which disappear and reappear based on user clicks and input. See also the
  // FormWithDefaultValueTextFields class, which automates use of this class.
  
  // CAUTION: Be careful using this with an input that writes to the database!
  // If the input field is not changed, the default string will be saved. One
  // solution is to instead instantiate a FormWithDefaultValueTextFields
  // object, which will clear these fields before submission.
  
  // Usage (two steps):
  // 1. Add HTML: <input id="users-new-username" title="username" />
  // 2. Add JS:   new DefaultValueTextField('users-new-username');
  // This automatically uses the input's title attribute as the default value.
  
  initialize:function(input){
    this.input = $(input);
    if (!this.input) { return }
    this.form = this.input.up('form');
    this.value = this.input.title;
    this.input.title = '';
    this.onblur();
    this.input.observe('focus', this.onfocus.bindAsEventListener(this));
    this.input.observe('blur', this.onblur.bindAsEventListener(this));
    this.form.observe('submit', this.onsubmit.bindAsEventListener(this));
  },
  reset:function(){
    this.input.setStyle({color:'#aaaaaa'}).value = this.value;
  },
  onfocus:function(ev){
    if ($F(this.input) == this.value){
      this.input.setStyle({color:'#000000'}).value = '';
      this.input.focus();
    }
  },
  onblur:function(ev){
    if ($F(this.input).blank()){ this.reset(); }
  },
  onsubmit: function(event) {
    if ($F(this.input) == this.value) {
      this.input.value = '';
    };
  }
});

document.observe('dom:loaded', function(event) {
  $$('a.disable_on_click').each(function(a) {
    a.observe('click', function(event) {
      link = event.target;
      if (link.hasClassName('unpublish')) {
        a.insert({before: '<span class="rejected" style="width: auto; border: 0; padding-left: 3px;">Please wait</span>'});
      } else {
        a.insert({before: '<span class="rejected" style="width: auto;">Please wait</span>'});
      };
      a.hide();
    });
  });
  
  $$('a[rel=external]').each(function(external_link) {
    external_link.observe('click', function(event){
      event.stop();
      window.open(event.element().readAttribute('href'), '_blank', '');
    })
  });
  
});

Event.addBehavior({
 '#inline-ringtone-terms-control' : InlineDropdown('inline-ringtone-terms-block')
});
Event.addBehavior({
 '#inline-ringtone-guidelines-control' : InlineDropdown('inline-ringtone-guidelines-block')
});
