
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) {
    bos_gn.html.action.proto.createUrl(url).dialog(null, options);
  },

  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 action, action_options = {};
  	if (typeof url == 'object') {
    	if (/form/i.test($(url).get(0).nodeName)) {
        var f = $(url).get(0);
        action = bos_gn.html.action.createUrl($(f).attr('action'), params);
        action_options['submit_el'] = f;
      }
    } else {
      action = bos_gn.html.action.createUrl(url, params);
    }

    if (typeof callback == 'function') action_options['callback'] = callback;
    action.dialog(action_options, options);
  },

  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_gn.html.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 = $.cookie(el_id+'_tab_selected');
  	index = index === null || index === undefined ? 0 : index; // first tab selected by default
    index = parseInt(index, 10);
    $(jel_id+' > ul').tabs('select', index);
  } else {
    $(jel_id).tabs(options);
  }
}

(function($) {

function initChoicer() {
  if (!$('#bos_choice_selector').length) {
    var choicer = $('<div id="bos_choice_selector" style="display:none"></div>')
            .css('outline', 0)
  //          .css('position', 'absolute')
            .addClass('ui-widget ui-widget-content ui-corner-all')
            .attr('tabIndex', -1)
            //title
            .append('<div class="ui-widget-header" style="padding: 3px"></div>')
            //content
            .append('<div class="list-content" style="padding:2px; overflow-y:scroll"></div>')
            .appendTo('body');

  }
}

function buildChoicer(choicer, $trigger, options) {
  var content = choicer.find('.list-content'),
      hide_box = true,
      $el = $trigger.parent().find('input'),
      $el_display = $trigger.parent('td').next('td');

  choicer.find('.ui-widget-header:first').html(options.title);

  choicer.css('width', options.width+'px')
         .unbind()
         .blur(function(eventObject) {
            if (hide_box) {
              content.get(0).scrollTop = 0;
              choicer.hide()
                .css('left', 0)
                .css('top', 0);
              content.empty();
            }
         })
        .undelegate()
        .delegate('li', 'click', function() {
          choicer.data('triggered_by_id', null);

          $el.val($(this).attr('value'));

          $el_display
            .html(bos_gn.util.source.parseTemplateByNames(options.res_tpl_name, options.src_name, $el.val()))
            .effect('pulsate', {times: 2}, 300);
          $trigger.trigger('change');

          hide_box = true;
          choicer.blur();
        })
        .delegate('*', 'mouseover mouseout', function(event) {
          if (event.type == 'mouseover') {
            hide_box = false;
            if ($(this).is('li')) {
              $(this).addClass('ui-state-default');
            }
          } else {
            hide_box = true;
            if ($(this).is('li')) {
              $(this).removeClass('ui-state-default');
            }
          }
        })
        .data('triggered_by_id', $trigger.attr('id'));

  content.css('height', options.height+'px')
         .append(bos_gn.util.source.parseTemplateByNames(options.dial_tpl_name, options.src_name, $el.val()))
         .find('li')
            .addClass('ui-widget-content')
         ;

  choicer
         .css('left', 0)
         .css('top', 0)
         .position({
            my: 'left top',
            at: 'right top',
            of: $trigger,
            offset: '5 -25',
            collision: 'fit fit'
         });
}

function scrollToActive(choicer) {
  var active_li = choicer.find('li.ui-state-active'),
      p_scroll,
      content = choicer.find('.list-content');

  if (active_li.length) {
//    content.offset({top:active_li.offset().top, left: content.offset().left})
    if (p_scroll = active_li.offset().top - content.offset().top) {
      content.get(0).scrollTop += (p_scroll - 20);
    }
  }
}

$.fn.bosChoicer = function(options) {
  options = $.extend({}, {
    width: 200,
    height: 240,
    title: 'Sélection',
    dial_tpl_name: null,
    res_tpl_name: null,
    src_name: null,
    ctx: null
  }, options);

  initChoicer();
  var choicer = $('#bos_choice_selector');

  $(this).mousedown(function() {
    if (choicer.is(':visible') && choicer.data('triggered_by_id') == $(this).attr('id')) {
      choicer.data('triggered_by_id', null);
      return;
    }
    choicer.blur();

    buildChoicer(choicer, $(this), options);
    choicer.show();
    scrollToActive(choicer);
//    setTimeout(function() {scrollToActive(choicer);}, 100);
  })
  .mouseup(function() {
    if (choicer.is(':visible')) {
      choicer.focus();
    }
  });

}

})(jQuery);


(function($) {

$.fn.bosTabButton = function(options) {
  options = $.extend({}, {use_cookie: false, add_all: false}, options);
  var str = '';
  $('.bos_button_tab', this).each(function() {
    str += '<button class="fg-button ui-widget-header ui-priority-primary" style="border-width:0px;" href="#'+$(this).attr('id')+'">'+$(this).attr('title')+'</button>';
    $(this).removeAttr('title');
  });

  if (options.add_all) str += '<button class="fg-button ui-widget-header ui-priority-primary" style="border-width:0px;">Tous</button>';

  if (!str) return;
  str += '<div style="clear:both"/>';
  var $div = $('<div id="'+$(this).attr('id')+'_container" class="fg-buttonset fg-buttonset-single"/>').append(str);
  $(this).prepend('<div style="clear:both"/>').prepend($div);

  var last_btn_ind = $('button', $div).length - 1,
      max_width = 0;

  $('button', $div).each(function(i) {
    if ($(this).width() > max_width) max_width = $(this).width();
    if (i == 0) {
      $(this).addClass('ui-state-active ui-corner-left');
    } else {
      $(this).css('border-width', '0 0 0 1px');
    }
    if (i == last_btn_ind) {
      $(this).addClass('ui-corner-right');
    }

    $(this).hover(
      function(){
        $(this).addClass("ui-state-hover");
      },
      function(){
        $(this).removeClass("ui-state-hover");
      }
    ).click(function() {
      var self = this;

      $(this).parent().find('button').each(function(index) {
        $(this).removeClass('ui-state-active');

        //si self n'a pas de href alors on ne cache rien
        //si this a un href et this != self alors on cache this
        //optimisation, sinon sur gros élement, l'écran blink
        if ($(self).attr('href') && $(this).attr('href') && self !== this) $($(this).attr('href')).hide();

        if (self === this && options.use_cookie) {
          $.cookie($div.attr('id')+'_bos_tab_btn', index);
        }
      });

      if ($(this).attr('href')) $($(this).attr('href')).show();

      $(this).addClass('ui-state-active');

      //si pas de href alors button = 'show all'
      if (!$(this).attr('href')) {
        $(this).parent().find('button').each(function() {
          if ($(this).attr('href')) $($(this).attr('href')).show();
        });
      }

      $(this).blur();
      return false;
    });

  });// end of each (button)

  $('button', $div).each(function() {
    $(this).width(max_width + 25);
  });

  if (options.use_cookie) {
    var index = $.cookie($div.attr('id')+'_bos_tab_btn');
    index = index === null || index === undefined ? 0 : index; // first tab selected by default
    index = parseInt(index, 10);
    $('button:eq('+index+')', $div).click();
  } else {
    $('button:eq(0)', $div).click();
  }
};

$.encHTML = function(html) {
  return html.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
};

$.fn.notEditable = function(options) {
  var def_options = {
    checkbox_replace_checked : '<img src="/bospmPlugin/images/toolbar/bullet_green.png" />',
    checkbox_replace_unchecked : '<img src="/bospmPlugin/images/toolbar/bullet_red.png" />'
  };
  options = $.extend({}, def_options, options);
  function inputNotEditable($el) {
    var text = false;

    if ($el.attr('type') == 'checkbox') {
      if ($el.attr('checked')) {
        text = options.checkbox_replace_checked;
      } else {
        text = options.checkbox_replace_unchecked;
      }
    } else {
      if ($el.is(':visible')) {
        text = $el.val().replace(/\n/gi, "<br/>");
      }
      $el.next('.bos-trigger').hide();
    }

    if (text !== false) {
      text = '<span style="width:'+$el.width()+'px;margin-right:'+$el.css('margin-right')+'">'+text+'</span>';
      $el.before(text);
      $el.hide();
    }
  }

  function selectNotEditable($el) {
    // Check visibility
    $el.hide();

    var selected = $el.find(':selected');
    if (selected.length > 0) {
      var text = [];
      selected.each(function() {
        text.push($(this).text());
      });
      text = '<span style="width:'+$el.width()+'px;margin-right:'+$el.css('margin-right')+'">'+$.encHTML(text.join(', '))+'</span>';
      $el.before(text);
    }
  }

  function preCheck(el) {
    var $el = $(el);
    if ($el.data('bos_validator')) $el.siblings('.fvalid').hide();

    if (!$el.data('bos_not_editable')) {
      $el.data('bos_not_editable', true);

      if ($el.attr('type') != 'hidden') {
        return $el;
      }
    }
    return false;
  }


  this.each(function() {
    var $el;
    if (/input|textarea/i.test(this.nodeName)) {
      $el = preCheck(this);
      if ($el) {
        inputNotEditable($el);
      }
    } else if (/select/i.test(this.nodeName)) {
      $el = preCheck(this);
      if ($el) {
        selectNotEditable($el);
      }

    } else {
      $('input:submit', this).remove();
      $('li.tb_element_save', this).remove();
      $('input, textarea', this).each(function() {
        var $el = preCheck(this);
        if ($el) {
          inputNotEditable($el);
        }
      });
      $('select', this).each(function() {
        var $el = preCheck(this);
        if ($el) {
          selectNotEditable($el);
        }
      });
    }
  });
};

$.fn.buttonize = function(side) {

  if (this.tagName == 'A') {
    $(this).buttonize_one(side);
  }

  this.each(function() {
    if (this.tagName == 'A') {
      $(this).buttonize_one(side);
    } else {
      $('a.ui-state-default', $(this)).each(function() {
        $(this).buttonize_one(side);
      });
    }
  });

  return this;
}

$.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).hasClass('bosscr_button')) {
    $(this).css('padding', '0.4em 0.6em');
  }
//  $(this).css('color', '#FFF');
  $(this).css('position', 'relative')
         .css('float', side)
         .css('height', '16px')
         .css('margin-' + opposite, '5px')
         .css('vertical-align', 'middle')
         .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);
};



$.formValidator = {};

$.extend($.formValidator, {
	defaults: {
		valid_img : '/bospmPlugin/images/icones/valid_input.png',
		unvalid_img : '/bospmPlugin/images/icones/invalid_input.png'
	},

	form_options_stack: {},

  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) {
    if (input_id.jquery) {
      $input = input_id;
    } else {
      $input = $('#'+input_id);
    }
    var $img = $input.nextAll('img.fvalid:first');
    var is_validated = $.formValidator.isInputValidated($input);
    if ($img.length && $img.attr('src').indexOf($.formValidator.defaults.valid_img) >= 0 && (!is_validated)) $img.attr('src', $.formValidator.defaults.unvalid_img);
    if ($img.length && $img.attr('src').indexOf($.formValidator.defaults.unvalid_img) >= 0 && (is_validated)) $img.attr('src', $.formValidator.defaults.valid_img);
  }

});


$.fn.extend({
	formValidator: function(options) {
//    if ($.support.input.required == true) return this;

		if ( !this.length )	return this;
		var form_handler = this[0];
		if (!$.nodeName(form_handler, "form")) return this;

		return this.map(function(){
			return $.nodeName(this, "form") ?
				$.makeArray(this.elements) : this;
		})
		.filter(function(){
			return this.name && ($(this).attr('required') || $(this).attr('pattern')) && !$(this).data('bos_not_editable') && !$(this).data('bos_validator');
		})
		.map(function(i, input){
		  var $input = $(input),
          $trigger = $(input).next('.bos-trigger');

//      //has already validation script and image indicator
//      if ($input.siblings('img.fvalid:first').length) return;
      $input.data('bos_validator', true).attr('bos-validator', 'true');

		  if ($trigger.length) {
		    $place = $trigger;
      } else  {
        $place = $input;
      }

      var is_validated = $.formValidator.isInputValidated($input);
      var $img;

      if (is_validated) {
        $img = $('<img src="'+$.formValidator.defaults.valid_img+'" class="fvalid formValidator_valid" align="top"></img>');
      } else {
        $img = $('<img src="'+$.formValidator.defaults.unvalid_img+'" class="fvalid formValidator_invalid" align="top"></img>');
      }

      if (parseInt($input.css('margin-right'))) {
        $img.css('margin-right', $input.css('margin-right'));
        $input.css('margin-right', '');
      } else if ($trigger.length && parseInt($trigger.css('margin-right'))) {
        $img.css('margin-right', $trigger.css('margin-right'));
        $trigger.css('margin-right', '');
      }

      $img.css('margin-left', '1px');
      $place.after($img);
      if ($input.is("select")) {
        $input.width(parseInt($input.width(), 10) - 9);
      } else {
        $input.width(parseInt($input.width(), 10) - 13);
      }



      $input.keydown(function(e) {
      	//if(e.ctrlKey||e.altKey) return true;
        var $el = $(this);
        setTimeout(function(){$.formValidator.validateInput($el)}, 10 )
      	return true;
    	});

      $input.change(function(e) {
        $.formValidator.validateInput($(this));
      	return true;
    	});
		});

	}
});


$.fn.bosctUploadify = function (options) {
  this.each(function() {
    var $input = $(this);
    var id = $input.attr('id');

    $input.uploadify(options);
    options = $.extend({hide_uploader: true}, options);
    $('#' + id + 'Uploader').css('vertical-align', 'bottom');

    if ($input.val()) {
      if (options.hide_uploader) $('#' + 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(options.deleteMsg)) {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('').trigger('change');
          $('#' + id + 'File').hide();
          if ($.isFunction(options.deleteCallback)) options.deleteCallback.call(this);
        },
        complete: function() {
          $.unblockUI();
        },
        error   : function(XMLHttpRequest, textStatus, errorThrown) {
          alert(errorThrown);
          $.unblockUI();
        }
      });
    });

  });
};


})(jQuery);

