// escape from parent frame
if (window != top) top.location.href = location.href;

$.fn.smartsearchbox = function(opt) {
    $(this).one('focus', function() {
      $(this).attr('value','');
    })
    .each(function() {
      if (jQuery.browser.safari) {
        this.setAttribute("type","search");
        opt = opt || {};
        $(this)
          .attr(opt)
          .css('width','100%')
          .siblings("input[type=submit]").hide();
      }
    });
}

$.fn.related = function(opt) {
  if(attr = $(this).attr('for')) {
    if( related = $('#' + attr) ) {
      return related;
    }
  }
  if(src = $(this).attr('src')) {
    if(src.indexOf('#') == 0) {
      if(related = $(src)) {
        return related
      }
    }
  }
  return false;
}

$.fn.validate = function(validator) {
  validator = validator || $(this).attr('id') || null;
	var txt = $(this).val().replace(/\s+/g, '');

  switch(validator) {
    case 'email':
      if( !txt.match(/^[\w_.-]+@([\w\-]+\.)+[a-z]+$/i) )
        return false;
    case 'url':
      var pre = 'http//';
    	if( txt.length > 7 && txt.indexOf(pre) != 0 )
    		txt = pre + txt;
    	if( !txt.match(/^http:\/\/[a-z\_\.\-\/]+\.[a-z]{2,5}$/) )
    	  return false;
  }
  return true;
}
$.fn.checkForm = function(opt) {
  $(this).submit(function() {
    opt = opt || {};
  	var error = null;
  	var validator = null;
	  $("label[for]", this).each(function() {
	    if( '' != $(this).next('span.required').text() ) {  //- est obligatoire
  	    var label = $(this);
  	    var input = label.related();
  	    validator = opt[input.attr('id')];
  	    if ( !input.attr("value") || !$(this).validate($(this)) ) {
  	      label.addClass('error');
  	      input.addClass('error');
    			if (error == null) error = input;
        }
        else {
  	      label.removeClass('error');
  	      input.removeClass('error');          
        }
	    } //  ----------------------------------------- fin obligatoire
    });
  	if(error) {
  		error.focus();
  		return false;
  	}
  	else
  		return true;
  });
}

$(document).ready(function(){	
  // Champ de recherche
  var txtLabel = 'Looking for...';
  // 
  var o = $('#s')
    .val(txtLabel)
    .smartsearchbox({
      'autosave':'com.john-noone',
      'results':'5'
    });
  // var o = $('#s');
  //  .val(txtLabel).attr("type","search");
  $('form#searchform').submit(function(){
   if($('input#s').val() == txtLabel) {
     alert('Are you really look for this ?');
     return false;
   }
   else if( $('input#s').val() == '' ) {
     alert('Specify your research !');
     return false;
   }
  });
  
  // Commentaire
  $('#commentform').each(function(){
    $(this).checkForm();
  });
});
