/* Push Play */

if ( window.addEvent ) {
    window.addEvent('domready', function() {

        // For each autoform
        $$('form.auto_form').each(function(form){
            // see if we already have an error container

            var container = $$('p.feedback#'+form.get('id')+'_errors strong');
            // if not, make one
            if ( container.length == 0 ) {
                para = new Element('p').set({
                    'class':'feedback',
                    'id':form.get('id')+'_errors'
                }).inject(form, 'before');
                container = new Element('strong').inject(para);                
            }
            // then add a span for each field to put its errors into, if one doesn't exist
            form.getElements('.autoform_field').each(function(field){
                var errors = $(field.get('name')+'_error');
                if ( errors == null ) {
                    container.grab(
                        new Element('span').set('id', field.get('name')+'_error')
                    );
                } else {
                    // if it already exists, move it into the container
                    container.grab(errors);
                }
            });
        });
        
        // Cancel buttons
        if ( $('cancel_button') ) {
            new Element('input').set({'value':'Cancel','type':'button'})
            .inject( $('cancel_button') )
            .addEvent('click',function(){
                window.location = window.location.pathname.replace(/^(\/[^\/]+\/)(.*)$/, '$1');
            });
        }        
    });


}

/**
 * From http://cass-hacks.com/articles/code/js_url_encode_decode/
 */
function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

