function clearDefault(object, defaultText, replaceText) {
	if (object.value == defaultText) {
		object.value = replaceText;    
	}
}

ConsoleWrapper = Class.create({
  startTime: null,

  initialize: function()
  {
    this.startTime = new Date();
    this.log( 'Console.initialize', 'Started');
  },

  log: function(what,str)
  {
    var now = new Date();
    var time = (now.getTime() - this.startTime.getTime())/1000;
    var logEntry = String.sprintf( '[%8.3fs] %-50s %s', time, what, str );

    if ( typeof( console ) != 'undefined' )
      console.log( logEntry );
    else if ( false )
      alert( logEntry );
  }
});

Console = new ConsoleWrapper;


Ajax.Dispatcher = Class.create(Ajax.Request, {
  initialize: function($super, url, options, id, scrollto ) {
    
    url = url+'#...UNIQ:'+String.random();
    options = Object.clone(options);
    options = Object.extend( {method: 'get', requestHeaders: {accept: 'text/json'}}, options );
      
    var onComplete = options.onComplete;
    options.onComplete = (function(response, json) {

      this.parseResponse(response);

      if (Object.isFunction(onComplete)) onComplete(response, json);
    }).bind(this);

    if ( id )
      Ajax.Loading.id = id;

    if ( scrollto )
      Ajax.Loading.scrollto = scrollto;

    Ajax.Loading.start();


    var onLoading = options.onLoading;
    options.onLoading = (function(response, json) {
      if (Object.isFunction(onLoading)) onLoading(response, json);
    });
    $super(url, options);
  },

  parseResponse: function(request) {
    Ajax.Loading.done();

    if ( request.responseJSON === null )
    {
      Console.log( 'Ajax.Dispatch.parseResponse', 'Failed to parse JSON' );
      Console.log( request.responseText );
      return;
    }
    var json = request.responseJSON;
    json.each( function(item) {
      Console.log( 'Ajax.Dispatcher.parseResponse', item.type);

      if (item.type==='debug') {}
      else if (item.type==='console.log')
      {
        Console.log( item.subject, item.string );
      }
      else if (item.type==='html.update')
      {
        //Console.log( 'Ajax.Dispatcher.parseResponse', 'Updating '+item.object.element+ "\n"+item.object.html );
        $$( item.object.element ).each( (function(element) {
          element.update( item.object.html );
        }).bind(item) );
      }
      else if (item.type==='attributes.update')
      {
        $$( item.object.element ).each( (function(element) {
          $H(item.object.attributes).each( (function(attribute) {
            element.writeAttribute( attribute.key, attribute.value );
          }).bind(element) );
        }).bind(item) );
      }
      else if (item.type==='javascript')
      {
        Console.log( 'javascript', item.object.javascript );
        eval( item.object.javascript );
      }
      else
      {
        Console.log( 'Ajax.Dispath.parseResponse', 'Type missing' );
      }
    });
  }
});

Ajax.Dispatch = function( url, options, id, scrollto )
{
  var ajax = new Ajax.Dispatcher(url, options, id, scrollto );
  return false;
}

Ajax.Loading = {
  count: 0,
  id: 'content',
  scrollto: false,
  timer: null,
  clone_position: true,

  start: function()
  {
    Ajax.Loading.count ++;
    if ( typeof(Ajax.Loading.id) == 'string' )
    {

//      Console.log( 'start', 'Ajax.Loading.count = '+Ajax.Loading.count );
      onScroll();
      //new Effect.Appear( 'loading', { from: 0, to: 0.8, duration: 0.3, queue: { scope: 'loading', position: 'end' } } );
      //new Effect.Appear( 'loading', { from: 0.8, to: 0.9, duration: 0.1, queue: { scope: 'loading', position: 'end' } } );

      if ( Ajax.Loading.clone_position) // && !Prototype.Browser.IE 
      {
        if ( $( Ajax.Loading.id ) )
        {
          $('loading_overlay').clonePosition( $( Ajax.Loading.id ) );
        }
      }
      
      Ajax.Loading.clone_position = true;

      new Effect.Appear( 'loading_overlay', { from: 0, to: 0.6, duration: 0.3, queue: { scope: 'loading_overlay', position: 'end' } } );
      //new Effect.Appear( 'loading_overlay', { from: 0.4, to: 0.5, duration: 0.1, queue: { scope: 'loading_overlay', position: 'end' } } );
  /*
      var checker = function(pe) {
        Console.log( 'checking', 'Ajax.Loading.count = '+this.count );
        if ( $( 'loading' ).visible() )
        {
          Console.log( '1' );
          if ( this.count <= 0 )
          {
            Console.log( '2a' );
            this.count = 0;
            this.id = 'content';
            this.scrollto = false;
            this.fade();
          }
          else
          {
            Console.log( '2b' );
            return;
          }
        }
        pe.stop();
      };

      new PeriodicalExecuter( checker.bind( Ajax.Loading ), 3 );
      */
    }
  },

  done: function()
  {

    Ajax.Loading.count --;
    if ( typeof(Ajax.Loading.id) == 'string'  )
    {
      //Console.log( 'done', 'Ajax.Loading.count = ' + Ajax.Loading.count );
      if ( true ) //Ajax.Loading.count <= 0 )
      {
        Ajax.Loading.count = 0;
        Ajax.Loading.fade();
        Ajax.Loading.id = 'content';
        if ( Ajax.Loading.scrollto )
          $( Ajax.Loading.scrollto ).scrollTo();
        Ajax.Loading.scrollto = false;
      }
    }
    Ajax.Loading.scrollto = false;
    Ajax.Loading.id = 'content';
  },

  fade: function()
  {
    onScroll();
    //new Effect.Fade( 'loading', { from: 0.9, to: 0, duration: 0.3, queue: { scope: 'loading', position: 'end' } } );
    $('loading_overlay').clonePosition( $( Ajax.Loading.id ) );
    new Effect.Fade( 'loading_overlay', { from: 0.6, to: 0, duration: 0.3, queue: { scope: 'loading_overlay', position: 'end' } } );
  }
}



function onLoad()
{
  onResize();
}



function onResize()
{
  onScroll();
}


function onScroll()
{
  if ( $('loading') )
  {
    $('loading').setStyle( {
      top: ($( Ajax.Loading.id ).cumulativeOffset().top + $( Ajax.Loading.id ).getHeight()/2 - 100 )+'px',
      left: ($( Ajax.Loading.id ).cumulativeOffset().left + $( Ajax.Loading.id ).getWidth()/2 - 150 )+'px'
    } );
  }

  if ( $('email') )
  {
    $('email').setStyle( {
      top: (document.viewport.getScrollOffsets().top + document.viewport.getHeight()/2 - $('email').getHeight()/2 )+'px',
      left: (document.viewport.getScrollOffsets().left + document.viewport.getWidth()/2 - $('email').getWidth()/2 )+'px'
    } );
  }
  
  if ( $('reaction_help') )
  {
    $('reaction_help').setStyle( {
      top: (document.viewport.getScrollOffsets().top + document.viewport.getHeight()/2 - $('reaction_help').getHeight()/2 )+'px',
      left: (document.viewport.getScrollOffsets().left + document.viewport.getWidth()/2 - $('reaction_help').getWidth()/2 )+'px'
    } );
  }
  
  if ( $('fileformats_help') )
  {
    $('fileformats_help').setStyle( {
      top: (document.viewport.getScrollOffsets().top + document.viewport.getHeight()/2 - $('fileformats_help').getHeight()/2 )+'px',
      left: (document.viewport.getScrollOffsets().left + document.viewport.getWidth()/2 - $('fileformats_help').getWidth()/2 )+'px'
    } );
  }
  
  if ( $('embedcode') )
  {
    $('embedcode').setStyle( {
      top: (document.viewport.getScrollOffsets().top + document.viewport.getHeight()/2 - $('embedcode').getHeight()/2 )+'px',
      left: (document.viewport.getScrollOffsets().left + document.viewport.getWidth()/2 - $('embedcode').getWidth()/2 )+'px'
    } );
  }

  if ( $('report_abuse') )
  {
    $('report_abuse').setStyle( {
      top: (document.viewport.getScrollOffsets().top + document.viewport.getHeight()/2 - $('report_abuse').getHeight()/2 )+'px',
      left: (document.viewport.getScrollOffsets().left + document.viewport.getWidth()/2 - $('report_abuse').getWidth()/2 )+'px'
    } );
  }

  if ( $('total_overlay_email') )
  {
    $('total_overlay_email').setStyle( {
      top: '0px',
      left: '0px',
      width: $(document.body).getWidth()+'px',
      height: $(document.body).getHeight()+'px'
    } );
  }
}



Respect = {
  Stars: function( count, info )
  {
    $( 'respect_points_info' ).update($('respect_points_hidden').innerHTML);
    if ( info )
    {
      infos = ['Super slecht', 'Slecht', 'Matig', 'Goed', 'Geweldig'];
      $( 'respect_points_info' ).update( infos[ count-1 ] );
    }


    elements = $$( '.starsImage' );

    for ( i = 0; i < count; i ++ )
      elements[i].src = '/images/star-icon.gif';

    for ( ; i < 5; i ++ )
      elements[i].src = '/images/star-icon-empty.gif';
  }
}



Photos = {
  pe: null,
  pe_stop: false,

  Scrollup: function( )
  {
    Photos.pe_stop = false;

    Photos.pe = new PeriodicalExecuter(
      function(pe) {
        if ( Photos.pe_stop )
        {
          pe.stop();
          return;
        }

        var newtop = (parseInt($('photos_wrapper').getStyle('top'))+2);
        if ( newtop >= 0 )
        {
          pe.stop();
          return;
        }

        $('photos_wrapper').setStyle( {
          top: newtop+'px'
        } );
      },
      0.01
    );
  },

  Scrolldown: function()
  {
    Photos.pe_stop = false;

    Photos.pe = new PeriodicalExecuter(
      function(pe) {
        if ( Photos.pe_stop )
        {
          pe.stop();
          return;
        }

        var newtop = (parseInt($('photos_wrapper').getStyle('top'))-2);
        if ( newtop <= -1*($('photos_wrapper').getHeight()-$('photos_wrapper_wrapper').getHeight() + 10) )
        {
          pe.stop();
          return;
        }

        $('photos_wrapper').setStyle( {
          top: newtop+'px'
        } );
      },
      0.01
    );
  },

  Scrollstop: function()
  {
    Photos.pe_stop = true;
  }
}


function smilies(smile){
	var veld = document.post.comment;
	if (document.selection){
		veld.focus();
		var selection = document.selection.createRange();
		selection.text = smile;
  	}else if (veld.selectionStart || veld.selectionStart == '0'){
		var startPos = veld.selectionStart;
		var endPos = veld.selectionEnd;
		veld.value = veld.value.substring(0, startPos) + smile + veld.value.substring(endPos, veld.value.length);
  	}else{
		veld.value += smile;
  	}
}



function smiliesC(text) {    
    bericht = document.post.comment.value; 
    bericht+=text; 
	    
    document.post.comment.value = bericht;
    document.post.comment.focus();
}



Upload = {
  id: null,
  
  pe: null,
  stop: false,
  cnt: 0,

  StartProgress: function( id )
  {
    Upload.id = id;
    Upload.stop = false;
    Upload.cnt = 0;

    Upload.ShowPage( 3 );

    Console.log( 'Upload', 'Start' );

    Upload.pe = new PeriodicalExecuter(
      function(pe) {
        if ( Upload.stop )
        {
          pe.stop();
          return;
        }
        
        Console.log( 'Upload', 'bar');

        Upload.cnt ++;
        Ajax.Dispatch('/upload/progressbar/'+Upload.id+'/'+Upload.cnt, {}, {}, {} );
      },
      1
    );
  },

  ShowPage: function( page )
  {
    ['page1','page2'].each(
      function(page)
      {
        $(page).hide();
      }
    );
    $('page'+page).show();
  },

  ShowUploadMethod: function( type, uniqueID )
  {
    ['page2_upload','page2_webcam'].each(
      function( id )
      {
        $(id).hide();
      }
    );
    if(type == "webcam"){
    	$('page2_'+type).show();
      $('webcam').show();
    	document.getElementById("webcam").innerHTML = '<iframe src="/upload/webcam/'+uniqueID+'" width="100%" height="475" frameborder="0" scrolling="no"></iframe>';
    	$('webcam').clonePosition( $('page2_'+type) );
    }else{
    	$('page2_'+type).show();
    	$('webcam').hide();
   	}
  },

  Webcam: {
    Done: function( id )
    {
      alert( 'Done: '+id );
    },
    Delete: function( id )
    {
      alert( 'Delete' + id );
    }
  }
}



Weblogs = {
  Toggle: function(id)
  {
    if ( $('blog'+id+'-more').visible() )
    {
      Weblogs.Show(id);
    }
    else
    {
      Weblogs.Hide(id);
    }
  },
  Show: function(id)
  {
    $('blog'+id+'-more').hide();
    $('blog'+id+'-less').show();
    $('blog'+id+'-content').setStyle({height:'auto'});
  },
  Hide: function(id)
  {
    $('blog'+id+'-more').show();
    $('blog'+id+'-less').hide();
    $('blog'+id+'-content').setStyle({height:'76px'});
  }
}



Events = {
  Toggle: function(id)
  {
    if ( !$('event'+id+'-full').visible() )
    {
      Events.Show(id);
    }
    else
    {
      Events.Hide(id);
    }
  },
  Show: function(id)
  {
    $('event'+id+'-short').hide();
    $('event'+id+'-full').show();
  },
  Hide: function(id)
  {
    $('event'+id+'-full').hide();
    $('event'+id+'-short').show();
  }
}


function AbsoluteUrls( string )
{
  var prefix = 'http://www.puremusic.nl/';
  string = string.replace( /"\//g, '"'+prefix );
  string = string.replace( /=\//g, '='+prefix );
  return string;
}


function toggleHelp(element){
    if(document.getElementById(element).style.display=='block'){
        document.getElementById(element).style.display='none';
    }else{
       document.getElementById(element).style.display='block';
    }
}
var ao1;

function switchUserType(type){
    
    if(ao1 == undefined){
        ao1 = document.getElementById('artistoption1').innerHTML;
        ao2 = document.getElementById('artistoption2').innerHTML;
        ao3 = document.getElementById('artistoption3').innerHTML;
        ao4 = document.getElementById('artistoption4').innerHTML;
    }
    
    if(type == 'artist'){
        document.getElementById('artistoption1').innerHTML = ao1;
        document.getElementById('artistoption2').innerHTML = ao2;
        document.getElementById('artistoption3').innerHTML = ao3;
        document.getElementById('artistoption4').innerHTML = ao4; 
    }else{
        document.getElementById('artistoption1').innerHTML = "";
        document.getElementById('artistoption2').innerHTML = "";
        document.getElementById('artistoption3').innerHTML = "";
        document.getElementById('artistoption4').innerHTML = ""; 
        
    }
    
}





function textAreasInit(){
	var fields = document.getElementsByTagName("textarea");
	for(var i=0; i<fields.length; i++){
		if(fields[i].getAttribute('maxlength') != undefined){
			fields[i].onkeyup = function(){
				var maxLength = parseInt(this.getAttribute('maxlength'));
				if(this.value.length > maxLength){
					this.value = this.value.substring(0,maxLength);
				}
			}
		}
	}
}

function forceMaxLength(){
	var maxLength = parseInt(this.getAttribute('maxlength'));
	if(this.value.length > maxlength){
		this.value = this.value.substring(0,maxlength);
	}
}
 
function addEvent(elm, evType, fn, useCapture){
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
	if(elm.addEventListener){
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}else if (elm.attachEvent){
		var r = elm.attachEvent("on"+evType, fn);
		return r;
	}else{
		//alert("Handler could not be removed");
   }
 }
 
 // Start check maxlength textarea
 addEvent(window, "load", textAreasInit);
