var guestbook = guestbook || {}; 

guestbook.conf = {
  handle  : '/dwb_guestbook/guestbook.php',
  open    :0,
  errors  : {
    invalid : 'Please verify the field values. Required fields can\'t by empty and the email field must be a valid email address.',
    connect : 'The connection with sever hasn\'t been established'
  }
}

guestbook.newInstance = function(gbContainer, gbForm){
  var gbContainer = '#'+gbContainer,
      gbForm      = '#'+gbForm,
      processing  = false;
      
  function _modifyItems(){
	  $(gbContainer+' .rating').each( function(){
                          var rating = parseInt($(this).text());
                          if(!isNaN(rating)){
                            var stars = '';
                            for(var i=0; i < rating; i++){stars += '<img src="/dwb_guestbook/style/star_on.gif" />';}
                            for(var i=rating; i < 5; i++){stars += '<img src="/dwb_guestbook/style/star_off.gif" />';}
                            $(this).html(stars);
                          }
                        }
    );
    
    $(gbContainer + ' .hreview-active').removeClass('hreview-active');
    $(gbContainer).accordion('destroy');
    $(gbContainer).accordion({active:false, autoHeight:true, clearStyle:true, event:'mouseover', header: '.guestbook-header', change:function(evt,ui){ $(ui.newHeader).parents('.hreview').toggleClass('hreview-active'); $(ui.oldHeader).parents('.hreview').toggleClass('hreview-active'); }});
    $(gbContainer).accordion('activate', 0);
  }
	
	// FORM METHODS
	
	function _formRequest(formData, jqForm){ 
	  var valid = true;
	  $(gbForm+' .not-empty').each(function(){
	      if(this['editor']){ $(this).val(this['editor'].getContent({save : true})) } 
	      if( /$(\s*|<br\/>|<html\/>)^/.test($(this).val())){ valid = false; }
	  });
	  
    $(gbForm+' .email-field').each(function(){ var val = $(this).val(); if(val.length > 0 && !/^\S+@\S+(\.\S+)*\.(\S{2,3}|info)$/i.test(val) || /[\(\)\<\>\,\;\:\\\"\[\]]/.test(val)){ valid = false; }});
	  if(!valid){ $('<div>'+guestbook.conf.errors.invalid+'</div>')._insertError(); }
    else{$(gbForm).parent().fadeTo('normal', 0.3)}
	  return valid;                             
	}
	
	function _replaceCaptcha(){
		$(gbForm+' .guestbook-captcha').attr('src', guestbook.conf.handle+"?secure_code_id="+($(gbForm+ ' input[name="secure_code_id"]').val())+"&t="+Math.random());
	}
	
	function _formResponse(data, status){
	  $(gbForm).parent().fadeTo('normal', 1);
	  data = (status == 'success') ? data : '<div>'+guestbook.conf.errors.connect+'</div>';
	  $('<div>'+data+'</div>').find('.error')._insertError().end().find('.hreview')._insertItem();
	  
	  // Replace the captcha image
	  _replaceCaptcha();
	  
	  // Set processing to false to permit new submits
	  processing = false;
	}
	
	jQuery.fn._insertError = function(){
	  if(this.length > 0){ $(gbForm+' .guestbook-error').append(this).show(); }  
	  return this;
	}
	
	jQuery.fn._insertItem = function(){
	  $(gbContainer).prepend($(this));
	  _modifyItems();
	  
	  // In this moment clear the form
	  if($(this).length > 0){
	  	$(gbForm).resetForm();
	  	$(gbForm+ ' textarea').each(function(){ if(this['editor']){ this['editor'].setContent(''); }});
	  }
	  return this;
	}
	// MAIN CODE HERE
	
	// Load guestbook items
	$(gbContainer+':empty').ajaxError(function(event, request, settings){$(gbForm).parent().fadeTo('normal', 1); $(gbForm + ' .guestbook-error').append(guestbook.conf.errors.connect+': ' +settings.url).show();}).load(guestbook.conf.handle, {'operation':'get'}, _modifyItems);
	
	// Set the reload captcha event handle and the 'reload' title
	$(gbForm+' .guestbook-captcha').click(_replaceCaptcha).attr('title', 'Reload Captcha');
	
	
  // Set a submit handle

	// Modify gbForm
	$(gbForm+':not(input[name="operation"])').append('<input type="hidden" name="operation" value="set" />');
	$(gbForm+':not(input[name="secure_code_id"])').append('<input type="hidden" name="secure_code_id" value="id'+(Math.floor(Math.random()*(1000+1)))+'" />');
	_replaceCaptcha();
	
	$(gbForm).submit(
	    function(){
	    	if(!processing){
	    		processing = true;	
	      	$(gbForm+' .guestbook-error').empty().hide();
	      	if(_formRequest()){
	      		$(gbForm + ' .secure_code').attr('name', $(gbForm+ ' input[name="secure_code_id"]').val()); 
	      		$.post(guestbook.conf.handle, $(gbForm).formSerialize(), _formResponse, 'html'); 
	      	}
	      }
	      return false;
      });
  
  // Function for ID generation
  if (!jQuery.generateId) {
    jQuery.generateId = function() {
      return arguments.callee.prefix + arguments.callee.count++;
    };
    
    jQuery.fn.generateId = function() {
        return this.each(function() {
        jQuery.generateId.prefix = this.name || 'anonymous';
        jQuery.generateId.count = 0;
        this.id = this.id || $.generateId();
      });
    };
  }
  
  // Replace textareas by a simple wyswyg editor
  $(gbForm + ' textarea').each(function(){ if(punymce){
                                              $(this).generateId();
                                              this['editor'] = new punymce.Editor({id : this.id});
                                           }
                                         }
  );
};


