
var bosFlexigrid = {
  send: function(lid, url, params) {
    if (params.length) {
      var o_url = $('#'+lid).getFlexOption('url');

      params.push({name: 'lid', value: lid});
      $('#'+lid).flexOptions({url: url, params: params});
      $('#'+lid).flexReload();
      $('#'+lid).flexOptions({url: o_url, params: null});
    }
  }
};

var bosDialog = {
  open : function(url, options) {
    jQuery('#bos_dialog_div_element').dialog('destroy').remove();
    if ($.fn.jquery == '1.2.6') {
      jQuery('<div id="bos_dialog_div_element" title="dialog box" class="default">loading...</div>').dialog(options).load(url);
    } else {
      jQuery('<div id="bos_dialog_div_element" title="dialog box">loading...</div>').dialog(options).load(url);
    }
  },

  options: function(options) {
    var val = jQuery('#bos_dialog_div_element').html();
    jQuery('#bos_dialog_div_element').dialog('destroy').remove();
    if ($.fn.jquery == '1.2.6') {
      jQuery('<div id="bos_dialog_div_element"title="dialog box" class="default">loading...</div>').html(val).dialog(options);
    } else {
      jQuery('<div id="bos_dialog_div_element"title="dialog box">loading...</div>').html(val).dialog(options);
    }
  },

  open_param : function(url, options, params, callback) {
  	var i = 0;

  	if (typeof url == 'object') {
    	if (/form/i.test($(url).get(0).nodeName)) {
        var f = $(url).get(0);
        var url = $(f).attr('action');

      	var f_options = $(f).serializeArray();

        for ( var key in params)
          f_options.push({name: key, value: params[key]});

      	params = f_options;
      }
    }
    if (url.lastIndexOf('?') == -1) url += '?';
    else url += '&';
    url += 'ts='+ new Date().getTime();

    jQuery('#bos_dialog_div_element').dialog('destroy').remove();
    if ($.fn.jquery == '1.2.6') {
      jQuery('<div id="bos_dialog_div_element" title="dialog box" class="default">loading...</div>').dialog(options).load(url, params);
    } else {
      jQuery('<div id="bos_dialog_div_element" title="dialog box">loading...</div>').dialog(options).load(url, params, callback);
    }
  },

  open_form : function(url, options, params) {
    $('#bos_dialog_div_element').dialog('destroy').remove();
    var cur_div = '';
    if ($.fn.jquery == '1.2.6') {
      cur_div = '<div id="bos_dialog_div_element" title="dialog box" class="default">loading...</div>';
    } else {
      cur_div = '<div id="bos_dialog_div_element" title="dialog box">loading...</div>';
    }
    $(cur_div).dialog(options).load(url, params, function() {
      var dialog = this;
      $('form:first', this).submit(function() {
        var f_options = $(this).serializeArray();
        bosDialog.open_form($(this).attr('action'), options, f_options);

        return false;
      });

    });
  },

  form_saved : function(data) {
    var form_saved = $('#bos_dialog_div_element').dialog('option', 'form_saved');
    if (typeof form_saved == 'function') {
      form_saved.call(this, data);
    }
  },

  close : function() {
    $('#bos_dialog_div_element').dialog('close');
  }
};



jQuery.getCss = function( url, media ) {
  url = 'http://'+window.location.hostname+url;

  jQuery( document.createElement('link') ).attr({
          href: url,
          media: media || 'screen',
          type: 'text/css',
          rel: 'stylesheet'
  }).appendTo('head');
};



function bosMakeTab(el_id, use_cookie, options) {

  if (typeof options == 'undefined') options = {};
  if (use_cookie) {
    options.cookie = {name: el_id, expires: 30};
  }

  var jel_id = '#'+ el_id;

  var tab_handler = '';

  $(jel_id).children('div').map(function() {
    if ($.fn.jquery == '1.2.6') {
      tab_handler += '<li><a href="#'+this.id+'"><span>'+$(this).attr('title')+'</span></a></li>';
    } else {
      tab_handler += '<li><a href="#'+this.id+'">'+$(this).attr('title')+'</a></li>';
    }
    $(this).removeAttr('title');
  });

  tab_handler = '<ul>'+tab_handler+'</ul>';
  $(jel_id).prepend(tab_handler);
  if ($.fn.jquery == '1.2.6') {
    $(jel_id+' > ul').tabs({
      select : function(event, ui) {
        $.cookie($(ui.panel).parent().attr('id')+'_tab_selected', ui.index);
      }
    });
    var index = parseInt($.cookie(el_id+'_tab_selected'), 10);
  	index = index === null || index !== undefined ? index : 0; // first tab selected by default
    $(jel_id+' > ul').tabs('select', index);
  } else {
    $(jel_id).tabs(options);
  }
}


(function($) {
$.encHTML = function(html) {
  return html.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
};

$.fn.notEditable = function() {
  function inputNotEditable(el) {
    if ($(el).attr('type') == 'checkbox') {
      if ($(el).attr('checked')) {
        $(el).after('<img src="/bospmPlugin/images/toolbar/bullet_green.png" />');
      } else {
        $(el).after('<img src="/bospmPlugin/images/toolbar/bullet_red.png" />');
      }
    } else if ($(el).attr('type') != 'hidden') {
      var str = $(el).val();
      $(el).after(str.replace(/\n/gi, "<br/>"));
      $(el).siblings('.ui-datepicker-trigger').hide();
    }

    $(el).hide();
  }

  function selectNotEditable(el) {
    $(el).hide();
    $(el).after($.encHTML($(':selected', el).text()));
  }


  this.each(function() {
    if (/input|textarea/i.test(this.nodeName)) {
      inputNotEditable(this);
    } else if (/select/i.test(this.nodeName)) {
      selectNotEditable(this);
    } else {
      $('input', this).each(function() {
        inputNotEditable(this);
      });
      $('textarea', this).each(function() {
        inputNotEditable(this);
      });
      $('select', this).each(function() {
        selectNotEditable(this);
      });
    }
  });
};

$.fn.buttonize = function(side) {
  this.each(function() {
    if (this.tagName == 'A') {
      $(this).buttonize_one(side);
    } else {
      $('a.ui-state-default', $(this)).each(function() {
        $(this).buttonize_one(side);
      });
    }
  });
}

$.fn.buttonize_one = function(side) {
  if (typeof side == 'undefined') {
    if (typeof $(this).attr('button_pos') != 'undefined') {
      side = $(this).attr('button_pos');
    } else {
      side = 'left';
    }
  }
  var opposite = (side == 'left') ? 'right' : 'left';
  if (!$(this).css('padding').length) {
    $(this).css('padding', '0.4em .6em');
  }
  $(this).css('position', 'relative');
  $(this).css('color', '#FFF');
  $(this).css('float', side);
  $(this).css('height', '16px');
  $(this).css('margin-' + opposite, '5px');
  $(this).css('vertical-align', 'middle');
  $(this).css('cursor', 'pointer');
  $(this).addClass('ui-corner-all');
  $(this).html('<span style="line-height:16px;">'+$(this).html()+'</span>');
  var ui_icon = $(this).attr('ui-icon');
  if (ui_icon) {
    $(this).html('<span class="ui-icon ui-icon-'+ui_icon+'" style="float:left; "/>&nbsp;'+$(this).html());
  }
  $(this).hover(
    function() {$(this).addClass('ui-state-hover');},
    function() {$(this).removeClass('ui-state-hover');}
  );
}


$.fn.bosLoad = function(url, params, callback) {

  if (url.lastIndexOf('?') == -1) url += '?';
  else url += '&';
  url += 'ts='+ new Date().getTime();

  return jQuery(this).load(url, params, callback);
};



$.fn.localLoad = function (url, options, callback) {
//	options = options || {};

  this.each(function() {
    var input = this;
    var $input = jQuery(input);
    if (!/tr/i.test($(this).parent().get(0).nodeName)) {$input.parent().block({message: null});}
    $input.bosLoad(url, options,
      function (responseText, textStatus, XMLHttpRequest) {
        if (!/tr/i.test($(this).parent().get(0).nodeName)) {$input.parent().unblock();}
    		if ($.isFunction(callback)) callback();
      }
    );
  });
};

$.localPost = function (el, update, options, callback) {
	options = options || {};

	//el = soit une form, soit un input, soit un autre élément contenu dans un form
	var $form = null;
  if (/form/i.test($(el).get(0).nodeName)) {
    $form = $(el);
  } else {
    if (/input/i.test($(el).get(0).nodeName)) {
      $form = $(el.form)
    } else {
      $form = $($(el).parents('form').get(0));
    }
  }

  var url = $form.attr('action');
  var $input = $('#'+update);

	var f_options = jQuery($form).serializeArray();
  for ( var key in options ) {
    f_options.push({name: key, value: options[key]});
  }
  jQuery($input).localLoad(url, f_options, callback);
};

//dhtml Suite serialize
$.dsSerialize = function (el) {
	return jQuery.dsParam(jQuery(el.form).serializeArray());
};

//dhtml Suite param
$.dsParam = function(a) {
	var s = [];

	// If an array was passed in, assume that it is an array
	// of form elements
	if ( a.constructor == Array || a.jquery ) {
		// Serialize the form elements
		jQuery.each( a, function(){
			s.push( this.name + "=" + this.value);
		});

	// Otherwise, assume that it's an object of key/value pairs
	} else {
		// Serialize the key/values
		for ( var j in a )
			// If the value is an array then the key names need to be repeated
			if ( a[j] && a[j].constructor == Array ) {
				jQuery.each(a[j], function(){
					s.push( j + "=" + this );
				});
			} else {
				s.push(j+ "=" + a[j]);
			}
	}
	// Return the resulting serialization
	return s.join("&").replace(/%20/g, "+");
};



$.formValidator = {};

$.extend($.formValidator, {
	defaults: {
		valid_img : '/bospmPlugin/images/icones/valid_input.png',
		unvalid_img : '/bospmPlugin/images/icones/invalid_input.png'
	},

	form_options_stack: {},

	getFormOptions: function(id) {
    return (this.form_options_stack[id] ? this.form_options_stack[id] : $.formValidator.defaults);
  },
	pushFormOptions: function(id, options) {
    this.form_options_stack[id] = options;
  },

  isInputValidated: function ($input) {
    re_not_number = /[^0-9.-]/;
    re_two_dot_pattern = /[0-9]*[.][0-9]*[.][0-9]*/;
    re_two_minus_pattern = /[0-9]*[-][0-9]*[-][0-9]*/;
    re_valid_real = /^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$/;
    re_valid_integer = /^([-]|[0-9])[0-9]*$/;

    var is_ok = true;
  	var val = $input.val();

    if ($input.attr('required') && !val) return false;

  	var pat = $input.attr('pattern');

    switch (pat) {
    case 'letter':
      is_ok = is_ok = /^[a-z]*$/i.test(val);
      break;

    case 'full-letter':
      is_ok = /^[a-zàâäéèêëîïôöùûüç]*$/i.test(val);
      break;

    case 'letter-space':
      is_ok = /^[a-z\s]*$/i.test(val);
      break;

    case 'full-letter-space':
      is_ok = /^[a-zàâäéèêëîïôöùûüç\s]*$/i.test(val);
      break;

    case 'email':
      is_ok = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i.test(val);
      break;

    //positive, negative, integer, float
    case 'numeric':
    case 'float':
      is_ok = !re_not_number.test(val) &&
              !re_two_dot_pattern.test(val) &&
              !re_two_minus.test(val) &&
              (re_valid_real.test(val) ||re_valid_integer.test(val));
      break;

    case 'unsigned':
      is_ok = !/[^0-9]/.test(val);
      break;

    case 'integer':
    case 'signed':
      is_ok = !/[^0-9-]/.test(val) && /^-[0-9]+$|^[0-9]+$/.test(val);
      break;
    }

    return is_ok;
  },

  validateInput : function(input_id) {
    $input = $('#'+input_id);
    var $img = $('#'+input_id+'_img');
    options = $.formValidator.getFormOptions($input[0].form.id || $input[0].form.name);
    var is_validated = $.formValidator.isInputValidated($input);
    if ($img.attr('src').indexOf(options.valid_img) >= 0 && (!is_validated)) $img.attr('src', options.unvalid_img);
    if ($img.attr('src').indexOf(options.unvalid_img) >= 0 && (is_validated)) $img.attr('src', options.valid_img);

  }

});


$.fn.extend({
	formValidator: function(options) {
		if ( !this.length )	return this;
		var form_handler = this[0];
		if (!$.nodeName(form_handler, "form")) return this;
		if (!(form_handler.id || form_handler.name)) return this;

    options = $.extend({}, $.formValidator.defaults, options);
		$.formValidator.pushFormOptions(form_handler.id || form_handler.name, options);

		return this.map(function(){
			return $.nodeName(this, "form") ?
				$.makeArray(this.elements) : this;
		})
		.filter(function(){
			return this.name && ($(this).attr('required') || $(this).attr('pattern'));
		})
		.map(function(i, input){
		  var $input = $(input);
		  var $trigger = $('#' + input.id + ' ~ img:first');// $('#trigger_'+input.id).length;
      var img_id = input.id+'_img';

      //has already validation script and image indicator
		  if($('#'+img_id).length) return;

		  if ($trigger.length) {
		    $place = $trigger;
      } else  {
        $place = $input;

      }
      var is_validated = $.formValidator.isInputValidated($input);
      var $img;

      if (is_validated) {
        $img = $('<img src="'+options.valid_img+'" id="'+img_id+'" class="formValidator_valid" align="top"></img>');
      } else {
        $img = $('<img src="'+options.unvalid_img+'" id="'+img_id+'" class="formValidator_invalid" align="top"></img>');
      }
      if ($input.css('margin-right')) {
        $img.css('margin-right', $input.css('margin-right'));
        $input.css('margin-right', '');
      }
      $img.css('margin-left', '1px');
      $place.after($img);
      if ($input.is("select")) {
        $input.width($input.width() - 9);
      } else {
        $input.width($input.width() - 13);
      }

      

      $input.keydown(function(e) {
      	//if(e.ctrlKey||e.altKey) return true;
        setTimeout("jQuery.formValidator.validateInput('"+this.id+"')", 10);

      	return true;
    	});

      $input.change(function(e) {
        $.formValidator.validateInput(this.id);
      	return true;
    	});
		});

	}
});


$.fn.bosctUploadify = function (options) {
  this.each(function() {
    var $input = $(this);
    var id = $input.attr('id');

    $input.uploadify(options);

    $('#' + id + 'Uploader').css('vertical-align', 'bottom');

    if ($input.val()) {
      $('#' + id + 'Uploader').hide();
      $('#' + id + 'File').show();
    } else {
      $('#' + id + 'Uploader').show();
      $('#' + id + 'File').hide();
    }

    $('#' + id + 'File').mouseover( function() {
      $(this).addClass('ui-state-default');
    });

    $('#' + id + 'File').mouseout( function() {
      $(this).removeClass('ui-state-default');
    });

    $('#' + id + 'Deleter').click( function() {

      if (!confirm('Are you sure ?')) {return;}

      $.ajax({
        'url'     : options.deleteScript + '?delete_id='+$input.val(),
        'beforeSend' : function() {
          $.blockUI();
        },
        'success' : function(data, textStatus) {
          $('#' + id + 'Uploader').show();

          $('#' + id + 'Downloader').attr('href', '#');

          $('#' + id + 'Name').text('');

          if ($('#' + id + 'Thumb').length) {
            $('#' + id + 'Thumb').attr('src', '/bosctPlugin/images/thumbs/no_img.png');
          }
          $input.val('');
          $('#' + id + 'File').hide();

          $.unblockUI();
        },
        'error'   : function(XMLHttpRequest, textStatus, errorThrown) {
          alert(errorThrown);
          $.unblockUI();
        }
      });
    });

  });
};


})(jQuery);
