// -----------------------------------------------------------------------
// Eros Fratini - eros@recoding.it
// jqprint 0.3
//
// - 19/06/2009 - some new implementations, added Opera support
// - 11/05/2009 - first sketch
//
// Printing plug-in for jQuery, evolution of jPrintArea: http://plugins.jquery.com/project/jPrintArea
// requires jQuery 1.3.x
//
// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
//------------------------------------------------------------------------

(function($) {
    var opt;

    $.fn.jqprint = function (options) {
        opt = $.extend({}, $.fn.jqprint.defaults, options);

        var $element = (this instanceof jQuery) ? this : $(this), doc;
        
        if (opt.operaSupport && $.browser.opera) 
        { 
            var tab = window.open("","jqPrint-preview");
            tab.document.open();

            doc = tab.document;
        }
        else 
        {
            var $iframe = $("<iframe  />");
        
            if (!opt.debug) { $iframe.css({ position: "absolute", width: "0px", height: "0px", left: "-600px", top: "-600px" }); }

            $iframe.appendTo("body");
            doc = $iframe[0].contentWindow.document;
        }
        
        if (opt.importCSS)
        {
            if ($("link[media=print]").length > 0) 
            {
                $("link[media=print]").each( function() {
                    doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' media='print' />");
                });
            }
            else 
            {
                $("link").each( function() {
                    doc.write("<link type='text/css' rel='stylesheet' href='" + $(this).attr("href") + "' />");
                });
            }
        }
        
        if (opt.printContainer) { doc.write($element.outer()); }
        else { $element.each( function() { doc.write($(this).html()); }); }
        
        doc.close();
        
        (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).focus();
        setTimeout( function() { (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).print(); if (tab) { tab.close(); } }, 1000);
    };
    
    $.fn.jqprint.defaults = {
		debug: false,
		importCSS: true, 
		printContainer: true,
		operaSupport: true
	};

    // Thanks to 9__, found at http://users.livejournal.com/9__/380664.html
    jQuery.fn.outer = function() {
      return $($('<div></div>').html(this.clone())).html();
    };
})(jQuery);;/*
 * jQuery clueTip plugin
 * Version 1.1pre  (May 16, 2010)
 * @requires jQuery v1.3+
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/*
 *
 * Full list of options/settings can be found at the bottom of this file and at http://plugins.learningjquery.com/cluetip/
 *
 * Examples can be found at http://plugins.learningjquery.com/cluetip/demo/
 *
*/

(function($) {
  $.cluetip = {version: '1.1pre'};
  var $cluetip, $cluetipInner, $cluetipOuter, $cluetipTitle, $cluetipArrows, $cluetipWait, $dropShadow, imgCount;
  var insertionType = 'appendTo', insertionElement = 'body';


  $.fn.cluetip = function(js, options) {
    if (typeof js == 'object') {
      options = js;
      js = null;
    }
    if (js == 'destroy') {
      return this.removeData('cluetip').unbind('.cluetip');
    }

    // merge per-call options with defaults
    options = $.extend(true, {}, $.fn.cluetip.defaults, options || {});

    /** =create cluetip divs **/

    if (!$('#cluetip').length) {
      $(['<div id="cluetip">',
        '<div id="cluetip-outer">',
          '<h3 id="cluetip-title"></h3>',
          '<div id="cluetip-inner"></div>',
        '</div>',
        '<div id="cluetip-extra"></div>',
        '<div id="cluetip-arrows" class="cluetip-arrows"></div>',
      '</div>'].join(''))
      [insertionType](insertionElement).hide();

      var cluezIndex = +options.cluezIndex;

      $cluetip = $('#cluetip').css({position: 'absolute'});
      $cluetipOuter = $('#cluetip-outer').css({position: 'relative', zIndex: cluezIndex});
      $cluetipInner = $('#cluetip-inner');
      $cluetipTitle = $('#cluetip-title');
      $cluetipArrows = $('#cluetip-arrows');
      $cluetipWait = $('<div id="cluetip-waitimage"></div>')
        .css({position: 'absolute'}).insertBefore($cluetip).hide();
    }
    var cluetipPadding = (parseInt($cluetip.css('paddingLeft'),10)||0) + (parseInt($cluetip.css('paddingRight'),10)||0);


    this.each(function(index) {
      var link = this, $this = $(this);

      // support metadata plugin (v1.0 and 2.0)
      var opts = $.extend(true, {}, options, $.metadata ? $this.metadata() : $.meta ? $this.data() : {});


      // start out with no contents (for ajax activation)
      var cluetipContents = false;

      cluezIndex = +opts.cluezIndex;
      $this.data('cluetip', {title: link.title, zIndex: cluezIndex});
      var isActive = false, closeOnDelay = 0;

      var tipAttribute = $this.attr(opts.attribute), ctClass = opts.cluetipClass;
      if (!tipAttribute && !opts.splitTitle && !js) {
        return true;
      }
      // if hideLocal is set to true, on DOM ready hide the local content that will be displayed in the clueTip
      if (opts.local && opts.localPrefix) {tipAttribute = opts.localPrefix + tipAttribute;}
      if (opts.local && opts.hideLocal) { $(tipAttribute + ':first').hide(); }
      var tOffset = parseInt(opts.topOffset, 10), lOffset = parseInt(opts.leftOffset, 10);
      // vertical measurement variables
      var tipHeight, wHeight,
          defHeight = isNaN(parseInt(opts.height, 10)) ? 'auto' : (/\D/g).test(opts.height) ? opts.height : opts.height + 'px';
      var sTop, linkTop, posY, tipY, mouseY, baseline;
      // horizontal measurement variables
      var tipInnerWidth = parseInt(opts.width, 10) || 275,
          tipWidth = tipInnerWidth + cluetipPadding + opts.dropShadowSteps,
          linkWidth = this.offsetWidth,
          linkLeft, posX, tipX, mouseX, winWidth;

      // parse the title
      var tipParts;
      var tipTitle = (opts.attribute != 'title') ? $this.attr(opts.titleAttribute) : '';
      if (opts.splitTitle) {
        if (tipTitle == undefined) {tipTitle = '';}
        tipParts = tipTitle.split(opts.splitTitle);
        tipTitle = tipParts.shift();
      }
      if (opts.escapeTitle) {
        tipTitle = tipTitle.replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;');
      }

      var localContent;
      function returnFalse() { return false; }

/***************************************
* ACTIVATION
****************************************/

//activate clueTip
    var activate = function(event) {
      if (!opts.onActivate($this)) {
        return false;
      }
      isActive = true;
      $cluetip.removeClass().css({width: tipInnerWidth});
      if (tipAttribute == $this.attr('href')) {
        $this.css('cursor', opts.cursor);
      }
      if (opts.hoverClass) {
        $this.addClass(opts.hoverClass);
      }
      linkTop = posY = $this.offset().top;
      linkLeft = $this.offset().left;
      mouseX = event.pageX;
      mouseY = event.pageY;
      if (link.tagName.toLowerCase() != 'area') {
        sTop = $(document).scrollTop();
        winWidth = $(window).width();
      }
// position clueTip horizontally
      if (opts.positionBy == 'fixed') {
        posX = linkWidth + linkLeft + lOffset;
        $cluetip.css({left: posX});
      } else {
        posX = (linkWidth > linkLeft && linkLeft > tipWidth)
          || linkLeft + linkWidth + tipWidth + lOffset > winWidth
          ? linkLeft - tipWidth - lOffset
          : linkWidth + linkLeft + lOffset;
        if (link.tagName.toLowerCase() == 'area' || opts.positionBy == 'mouse' || linkWidth + tipWidth > winWidth) { // position by mouse
          if (mouseX + 20 + tipWidth > winWidth) {
            $cluetip.addClass(' cluetip-' + ctClass);
            posX = (mouseX - tipWidth - lOffset) >= 0 ? mouseX - tipWidth - lOffset - parseInt($cluetip.css('marginLeft'),10) + parseInt($cluetipInner.css('marginRight'),10) :  mouseX - (tipWidth/2);
          } else {
            posX = mouseX + lOffset;
          }
        }
        var pY = posX < 0 ? event.pageY + tOffset : event.pageY;
        $cluetip.css({
          left: (posX > 0 && opts.positionBy != 'bottomTop') ? posX : (mouseX + (tipWidth/2) > winWidth) ? winWidth/2 - tipWidth/2 : Math.max(mouseX - (tipWidth/2),0),
          zIndex: $this.data('cluetip').zIndex
        });
        $cluetipArrows.css({zIndex: $this.data('cluetip').zIndex+1});
      }
        wHeight = $(window).height();

/***************************************
* load a string from cluetip method's first argument
***************************************/
      if (js) {
        if (typeof js == 'function') {
          js = js.call(link);
        }
        $cluetipInner.html(js);
        cluetipShow(pY);
      }
/***************************************
* load the title attribute only (or user-selected attribute).
* clueTip title is the string before the first delimiter
* subsequent delimiters place clueTip body text on separate lines
***************************************/

      else if (tipParts) {
        var tpl = tipParts.length;
        $cluetipInner.html(tpl ? tipParts[0] : '');
        if (tpl > 1) {
          for (var i=1; i < tpl; i++){
            $cluetipInner.append('<div class="split-body">' + tipParts[i] + '</div>');
          }
        }
        cluetipShow(pY);
      }
/***************************************
* load external file via ajax
***************************************/

      else if (!opts.local && tipAttribute.indexOf('#') !== 0) {
        if (/\.(jpe?g|tiff?|gif|png)$/i.test(tipAttribute)) {
          $cluetipInner.html('<img src="' + tipAttribute + '" alt="' + tipTitle + '" />');
          cluetipShow(pY);
        } else if (cluetipContents && opts.ajaxCache) {
          $cluetipInner.html(cluetipContents);
          cluetipShow(pY);
        } else {
          var optionBeforeSend = opts.ajaxSettings.beforeSend,
              optionError = opts.ajaxSettings.error,
              optionSuccess = opts.ajaxSettings.success,
              optionComplete = opts.ajaxSettings.complete;
          var ajaxSettings = {
            cache: false, // force requested page not to be cached by browser
            url: tipAttribute,
            beforeSend: function(xhr) {
              if (optionBeforeSend) {optionBeforeSend.call(link, xhr, $cluetip, $cluetipInner);}
              $cluetipOuter.children().empty();
              if (opts.waitImage) {
                $cluetipWait
                .css({top: mouseY+20, left: mouseX+20, zIndex: $this.data('cluetip').zIndex-1})
                .show();
              }
            },
            error: function(xhr, textStatus) {
              if (isActive) {
                if (optionError) {
                  optionError.call(link, xhr, textStatus, $cluetip, $cluetipInner);
                } else {
                  $cluetipInner.html('<i>sorry, the contents could not be loaded</i>');
                }
              }
            },
            success: function(data, textStatus) {
              cluetipContents = opts.ajaxProcess.call(link, data);
              if (isActive) {
                if (optionSuccess) {optionSuccess.call(link, data, textStatus, $cluetip, $cluetipInner);}
                $cluetipInner.html(cluetipContents);
              }
            },
            complete: function(xhr, textStatus) {
              if (optionComplete) {optionComplete.call(link, xhr, textStatus, $cluetip, $cluetipInner);}
              var imgs = $cluetipInner[0].getElementsByTagName('img');
              imgCount = imgs.length;
              for (var i=0, l = imgs.length; i < l; i++) {
                if (imgs[i].complete) {
                  imgCount--;
                }
              }
              if (imgCount && !$.browser.opera) {
                $(imgs).bind('load error', function() {
                  imgCount--;
                  if (imgCount<1) {
                    $cluetipWait.hide();
                    if (isActive) { cluetipShow(pY); }
                  }
                });
              } else {
                $cluetipWait.hide();
                if (isActive) { cluetipShow(pY); }
              }
            }
          };
          var ajaxMergedSettings = $.extend(true, {}, opts.ajaxSettings, ajaxSettings);

          $.ajax(ajaxMergedSettings);
        }

/***************************************
* load an element from the same page
***************************************/
      } else if (opts.local) {

        var $localContent = $(tipAttribute + (/#\S+$/.test(tipAttribute) ? '' : ':eq(' + index + ')')).clone(true).show();
        if (opts.localIdSuffix) {
          $localContent.attr('id', $localContent[0].id + opts.localIdSuffix);
        }
        $cluetipInner.html($localContent);
        cluetipShow(pY);
      }
    };

// get dimensions and options for cluetip and prepare it to be shown
    var cluetipShow = function(bpY) {
      $cluetip.addClass('cluetip-' + ctClass);
      if (opts.truncate) {
        var $truncloaded = $cluetipInner.text().slice(0,opts.truncate) + '...';
        $cluetipInner.html($truncloaded);
      }

      function doNothing() {}; //empty function
      tipTitle ? $cluetipTitle.show().html(tipTitle) : (opts.showTitle) ? $cluetipTitle.show().html('&nbsp;') : $cluetipTitle.hide();
      if (opts.sticky) {
        var $closeLink = $('<div id="cluetip-close"><a href="#">' + opts.closeText + '</a></div>');
        (opts.closePosition == 'bottom') ? $closeLink.appendTo($cluetipInner) : (opts.closePosition == 'title') ? $closeLink.prependTo($cluetipTitle) : $closeLink.prependTo($cluetipInner);
        $closeLink.bind('click.cluetip', function() {
          cluetipClose();
          return false;
        });
        if (opts.mouseOutClose) {
          $cluetip.bind('mouseleave.cluetip', function() {
            cluetipClose();
          });
        } else {
          $cluetip.unbind('mouseleave.cluetip');
        }
      }
// now that content is loaded, finish the positioning
      var direction = '';
      $cluetipOuter.css({zIndex: $this.data('cluetip').zIndex, overflow: defHeight == 'auto' ? 'visible' : 'auto', height: defHeight});
      tipHeight = defHeight == 'auto' ? Math.max($cluetip.outerHeight(),$cluetip.height()) : parseInt(defHeight,10);
      tipY = posY;
      baseline = sTop + wHeight;
      if (opts.positionBy == 'fixed') {
        tipY = posY - opts.dropShadowSteps + tOffset;
      } else if ( (posX < mouseX && Math.max(posX, 0) + tipWidth > mouseX) || opts.positionBy == 'bottomTop') {
        if (posY + tipHeight + tOffset > baseline && mouseY - sTop > tipHeight + tOffset) {
          tipY = mouseY - tipHeight - tOffset;
          direction = 'top';
        } else {
          tipY = mouseY + tOffset;
          direction = 'bottom';
        }
      } else if ( posY + tipHeight + tOffset > baseline ) {
        tipY = (tipHeight >= wHeight) ? sTop : baseline - tipHeight - tOffset;
      } else if ($this.css('display') == 'block' || link.tagName.toLowerCase() == 'area' || opts.positionBy == "mouse") {
        tipY = bpY - tOffset;
      } else {
        tipY = posY - opts.dropShadowSteps;
      }
      if (direction == '') {
        posX < linkLeft ? direction = 'left' : direction = 'right';
      }
      $cluetip.css({top: tipY + 'px'}).removeClass().addClass('clue-' + direction + '-' + ctClass).addClass(' cluetip-' + ctClass);
      if (opts.arrows) { // set up arrow positioning to align with element
        var bgY = (posY - tipY - opts.dropShadowSteps);
        $cluetipArrows.css({top: (/(left|right)/.test(direction) && posX >=0 && bgY > 0) ? bgY + 'px' : /(left|right)/.test(direction) ? 0 : ''}).show();
      } else {
        $cluetipArrows.hide();
      }

// (first hide, then) ***SHOW THE CLUETIP***
      // handle dropshadow divs first
      $dropShadow = createDropShadows(opts);
      if ($dropShadow && $dropShadow.length) {
        $dropShadow.hide().css({height: tipHeight, width: tipInnerWidth, zIndex: $this.data('cluetip').zIndex-1}).show();
      }

      $cluetip.hide()[opts.fx.open](opts.fx.openSpeed || 0);
      if ($.fn.bgiframe) { $cluetip.bgiframe(); }
      // delayed close (not fully tested)
      if (opts.delayedClose > 0) {
        closeOnDelay = setTimeout(cluetipClose, opts.delayedClose);
      }
      // trigger the optional onShow function
      opts.onShow.call(link, $cluetip, $cluetipInner);
    };

/***************************************
   =INACTIVATION
-------------------------------------- */
    var inactivate = function(event) {
      isActive = false;
      $cluetipWait.hide();
      if (!opts.sticky || (/click|toggle/).test(opts.activation) ) {
        cluetipClose();
        clearTimeout(closeOnDelay);
      }
      if (opts.hoverClass) {
        $this.removeClass(opts.hoverClass);
      }
    };
// close cluetip and reset some things
    var cluetipClose = function() {
      $cluetipOuter
      .parent().hide().removeClass();
      opts.onHide.call(link, $cluetip, $cluetipInner);
      $this.removeClass('cluetip-clicked');
      if (tipTitle) {
        $this.attr(opts.titleAttribute, tipTitle);
      }
      $this.css('cursor','');
      if (opts.arrows) {
        $cluetipArrows.css({top: ''});
      }
    };

    $(document).bind('hideCluetip', function(e) {
      cluetipClose();
    });
/***************************************
   =BIND EVENTS
-------------------------------------- */
  // activate by click
      if ( (/click|toggle/).test(opts.activation) ) {
        $this.bind('click.cluetip', function(event) {
          if ($cluetip.is(':hidden') || !$this.is('.cluetip-clicked')) {
            activate(event);
            $('.cluetip-clicked').removeClass('cluetip-clicked');
            $this.addClass('cluetip-clicked');
          } else {
            inactivate(event);
          }
          this.blur();
          return false;
        });
  // activate by focus; inactivate by blur
      } else if (opts.activation == 'focus') {
        $this.bind('focus.cluetip', function(event) {
          activate(event);
        });
        $this.bind('blur.cluetip', function(event) {
          inactivate(event);
        });
  // activate by hover
      } else {
        // clicking is returned false if clickThrough option is set to false
        $this[opts.clickThrough ? 'unbind' : 'bind']('click', returnFalse);
        //set up mouse tracking
        var mouseTracks = function(evt) {
          if (opts.tracking == true) {
            var trackX = posX - evt.pageX;
            var trackY = tipY ? tipY - evt.pageY : posY - evt.pageY;
            $this.bind('mousemove.cluetip', function(evt) {
              $cluetip.css({left: evt.pageX + trackX, top: evt.pageY + trackY });
            });
          }
        };
        if ($.fn.hoverIntent && opts.hoverIntent) {
          $this.hoverIntent({
            sensitivity: opts.hoverIntent.sensitivity,
            interval: opts.hoverIntent.interval,
            over: function(event) {
              activate(event);
              mouseTracks(event);
            },
            timeout: opts.hoverIntent.timeout,
            out: function(event) {inactivate(event); $this.unbind('mousemove.cluetip');}
          });
        } else {
          $this.bind('mouseenter.cluetip', function(event) {
            activate(event);
            mouseTracks(event);
          })
          .bind('mouseleave.cluetip', function(event) {
            inactivate(event);
            $this.unbind('mousemove.cluetip');
          });
        }

        $this.bind('mouseover.cluetip', function(event) {
          $this.attr('title','');
        }).bind('mouseleave.cluetip', function(event) {
          $this.attr('title', $this.data('cluetip').title);
        });
      }
    });

    /** =private functions
    ************************************************************/
    /** =create dropshadow divs **/

    function createDropShadows(options, newDropShadow) {
      var dropShadowSteps = (options.dropShadow && options.dropShadowSteps) ? +options.dropShadowSteps : 0;
      if ($.support.boxShadow) {
        var dsOffsets = dropShadowSteps === 0 ? '0 0 ' : '1px 1px ';
        $('#cluetip').css($.support.boxShadow, dsOffsets + dropShadowSteps + 'px rgba(0,0,0,0.5)');
        return false;
      }
      var oldDropShadow = $('#cluetip .cluetip-drop-shadow');
      if (dropShadowSteps == oldDropShadow.length) {
        return oldDropShadow;
      }
      oldDropShadow.remove();
      var dropShadows = [];
      for (var i=0; i < dropShadowSteps;) {
        dropShadows[i++] = '<div style="top:' + i + 'px;left:' + i + 'px;"></div>';
      }

      newDropShadow = $(dropShadows.join(''))
      .css({
        position: 'absolute',
        backgroundColor: '#FFF',
        zIndex: cluezIndex -1
      })
      .addClass('cluetip-drop-shadow')
      .prependTo('#cluetip');
      return newDropShadow;

    }


    return this;
  };

  (function() {
    $.support = $.support || {};
    // check support for CSS3 properties (currently only boxShadow)
    var div = document.createElement('div'),
        divStyle = div.style,
        styleProps = ['boxShadow'],
        prefixes = ['moz', 'Moz', 'webkit', 'o'];

    for (var i=0, sl = styleProps.length; i < sl; i++) {
      var prop = styleProps[i],
          uProp = prop.charAt(0).toUpperCase() + prop.slice(1);

      if ( typeof divStyle[ prop ] !== 'undefined' ) {
        $.support[ prop ] = prop;
      } else {
        for (var j=0, pl = prefixes.length; j < pl; j++) {

          if (typeof divStyle[ prefixes[j] + uProp ] !== 'undefined') {
            $.support[ prop ] = prefixes[j] + uProp;
            break;
          }
        }
      }
    }
    div = null; delete div;
  })();

/*
 * options for clueTip
 *
 * each one can be explicitly overridden by changing its value.
 * for example: $.fn.cluetip.defaults.width = 200;
 * would change the default width for all clueTips to 200.
 *
 * each one can also be overridden by passing an options map to the cluetip method.
 * for example: $('a.example').cluetip({width: 200});
 * would change the default width to 200 for clueTips invoked by a link with class of "example"
 *
 */

  $.fn.cluetip.defaults = {  // set up default options
    width:            'auto',      // The width of the clueTip
    height:           'auto',   // The height of the clueTip
    cluezIndex:       9999,       // Sets the z-index style property of the clueTip
    positionBy:       'auto',   // Sets the type of positioning: 'auto', 'mouse','bottomTop', 'fixed'
    topOffset:        5,       // Number of px to offset clueTip from top of invoking element
    leftOffset:       5,       // Number of px to offset clueTip from left of invoking element
    local:            false,    // Whether to use content from the same page for the clueTip's body
    localPrefix:      null,       // string to be prepended to the tip attribute if local is true
    localIdSuffix:    null,     // string to be appended to the cluetip content element's id if local is true
    hideLocal:        true,     // If local option is set to true, this determines whether local content
                                // to be shown in clueTip should be hidden at its original location
    attribute:        'rel',    // the attribute to be used for fetching the clueTip's body content
    titleAttribute:   'title',  // the attribute to be used for fetching the clueTip's title
    splitTitle:       '',       // A character used to split the title attribute into the clueTip title and divs
                                // within the clueTip body. more info below [6]
    escapeTitle:      false,    // whether to html escape the title attribute
    showTitle:        false,     // show title bar of the clueTip, even if title attribute not set
    cluetipClass:     '',// class added to outermost clueTip div in the form of 'cluetip-' + clueTipClass.
    hoverClass:       '',       // class applied to the invoking element onmouseover and removed onmouseout
    waitImage:        true,     // whether to show a "loading" img, which is set in jquery.cluetip.css
    cursor:           'help',
    arrows:           false,    // if true, displays arrow on appropriate side of clueTip
    dropShadow:       false,     // set to false if you don't want the drop-shadow effect on the clueTip
    dropShadowSteps:  6,        // adjusts the size of the drop shadow
    sticky:           false,    // keep visible until manually closed
    mouseOutClose:    false,    // close when clueTip is moused out
    activation:       'hover',  // set to 'click' to force user to click to show clueTip
                                // set to 'focus' to show on focus of a form element and hide on blur
    clickThrough:     false,    // if true, and activation is not 'click', then clicking on link will take user to the link's href,
                                // even if href and tipAttribute are equal
    tracking:         false,    // if true, clueTip will track mouse movement (experimental)
    delayedClose:     0,        // close clueTip on a timed delay (experimental)
    closePosition:    'top',    // location of close text for sticky cluetips; can be 'top' or 'bottom' or 'title'
    closeText:        'Close',  // text (or HTML) to to be clicked to close sticky clueTips
    truncate:         0,        // number of characters to truncate clueTip's contents. if 0, no truncation occurs

    // effect and speed for opening clueTips
    fx: {
                      open:       'show', // can be 'show' or 'slideDown' or 'fadeIn'
                      openSpeed:  ''
    },

    // settings for when hoverIntent plugin is used
    hoverIntent: {
                      sensitivity:  3,
              			  interval:     50,
              			  timeout:      0
    },

    // short-circuit function to run just before clueTip is shown.
    onActivate:       function(e) {return true;},
    // function to run just after clueTip is shown.
    onShow:           function(ct, ci){},
    // function to run just after clueTip is hidden.
    onHide:           function(ct, ci){},
    // whether to cache results of ajax request to avoid unnecessary hits to server
    ajaxCache:        true,

    // process data retrieved via xhr before it's displayed
    ajaxProcess:      function(data) {
                        data = data.replace(/<(script|style|title)[^<]+<\/(script|style|title)>/gm, '').replace(/<(link|meta)[^>]+>/g,'');
                        return data;
    },

    // can pass in standard $.ajax() parameters. Callback functions, such as beforeSend,
    // will be queued first within the default callbacks.
    // The only exception is error, which overrides the default
    ajaxSettings: {
                      // error: function(ct, ci) { /* override default error callback */ }
                      // beforeSend: function(ct, ci) { /* called first within default beforeSend callback }
                      dataType: 'html'
    },
    debug: false
  };


/*
 * Global defaults for clueTips. Apply to all calls to the clueTip plugin.
 *
 * @example $.cluetip.setup({
 *   insertionType: 'prependTo',
 *   insertionElement: '#container'
 * });
 *
 * @property
 * @name $.cluetip.setup
 * @type Map
 * @cat Plugins/tooltip
 * @option String insertionType: Default is 'appendTo'. Determines the method to be used for inserting the clueTip into the DOM. Permitted values are 'appendTo', 'prependTo', 'insertBefore', and 'insertAfter'
 * @option String insertionElement: Default is 'body'. Determines which element in the DOM the plugin will reference when inserting the clueTip.
 *
 */

  var insertionType = 'appendTo', insertionElement = 'body';

  $.cluetip.setup = function(options) {
    if (options && options.insertionType && (options.insertionType).match(/appendTo|prependTo|insertBefore|insertAfter/)) {
      insertionType = options.insertionType;
    }
    if (options && options.insertionElement) {
      insertionElement = options.insertionElement;
    }
  };

})(jQuery);
;(function ($) {
    $.fn.nicoslider = function (options) {
        var defaults = {
            start: 0,
            color: '#F6F2F1',
            sliderHeight: false
        };

        var opts = $.extend({}, $.fn.nicoslider.defaults, defaults, options);

        return this.each(function () {
            new nicoslide(this, opts);
        });
    };


    var nicoslide = function (slider, o) {
        var $slider = $(slider);

        $sliderWidth = $slider.parent().innerWidth();

        $sliderCss = {
            'width': $sliderWidth,
            'background-color': o.color
        };

        $slider.css($sliderCss);

        var ul = $slider.find("ul");
        var ulWidth = 0;
        var liHeight = 0;

        $slider.find("li").each(function () {
            ulWidth += $(this).width() + 5;
            ulWidth += parseInt($(this).css("padding-left"));
            ulWidth += parseInt($(this).css("padding-right"));
            ulWidth += parseInt($(this).css("margin-left"));
            ulWidth += parseInt($(this).css("margin-right"));
            liHeight = Math.max(liHeight, $(this).outerHeight());
        });
        //5 % of slider width
        $scrollWidth = Math.round(parseInt($sliderWidth) * parseFloat("0.05"));
        //min 30 px;
        if ($scrollWidth < 30) {
            $scrollWidth = 30;
        }

        var $wrapperWidth = Math.round(parseInt($sliderWidth) - ( 2 * $scrollWidth ));

        if (ulWidth > $wrapperWidth) {
            ul.wrapAll("<div class='wrapper'></div>");
            $wrapper = $slider.find(".wrapper");
            $ulHeight = ul.height();
            $wrapper.width($wrapperWidth);
            $wrapper.height($ulHeight);

            $wrapperCss = {
                'overflow': 'hidden',
                'float': 'left',
                'position': 'relative'
            };

            $wrapper.css($wrapperCss);
            ul.css('position', 'absolute');
            ul.width(ulWidth);
            $slider.prepend("<div class='scrollleft'></div>");
            $slider.append("<div class='scrollright'></div>");

            var rightScroll = $slider.find(".scrollright");
            var leftScroll = $slider.find(".scrollleft");

            rightScroll.append("<div class='rb'>&gt;</div>");
            leftScroll.append("<div class='lb'>&lt;</div>");

            $("div.rb").css('float', 'right');

            rightCss = {
                'width': $scrollWidth - ($wrapper.outerWidth(true) - $wrapper.innerWidth()),
                'height': liHeight + 5,
                'float': 'right',
                'background-color': o.color,
                'cursor': 'pointer',
                ' user-select': 'none'
            };

            leftCss = {
                'width': $scrollWidth - ($wrapper.outerWidth(true) - $wrapper.innerWidth()),
                'height': liHeight + 5,
                'float': 'left',
                'background-color': o.color,
                'cursor': 'pointer',
                ' user-select': 'none'
            };

            leftScroll.css(leftCss);
            rightScroll.css(rightCss);

            var rightScrollWidth = rightScroll.width();
            var leftScrollWidth = leftScroll.width();
            var scrollXpos = 0;
            var scrollStepSpeed = 40;
            var speed = 8;
            var shift = o.start;


            //scroll a droite
            rightScroll.bind("click", function (e) {
                var x = e.pageX - ($(this).offset().left);
                scrollXpos = Math.round((x / rightScrollWidth) * scrollStepSpeed);
                shift += (scrollXpos * speed);

                if (shift > (ulWidth - $wrapperWidth) + 50) {
                    shift = (ulWidth - $wrapperWidth) + 50;
                }
                ul.animate({
                    left: -shift
                }, 1);
            });

            //scroll a gauche
            leftScroll.bind("click", function (e) {
                var x = $(this).innerWidth() - (e.pageX - $(this).offset().left);

                scrollXpos = Math.round((x / leftScrollWidth) * scrollStepSpeed);
                shift -= (scrollXpos * speed);

                if (shift < 0) {
                    shift = 0;
                }

                ul.animate({
                    left: -shift
                }, 1);

            });
        }
    };
})(jQuery);
;/*
 * jQuery gvChart plugin
 * This plugin was created to simplify things when using Google Visualisation Charts. 
 * It still needs to be used with google script import tag, however now you can
 * crate chart from your table. 
 * All examples you will find on http://www.ivellios.toron.pl/technikalia/demos/gvChart/
 * @name jquery.gvChart-1.0.1.js
 * @author Janusz Kamieński - http://www.ivellios.toron.pl/technikalia
 * @version 1.0.1
 * @date December 04, 2010
 * @category jQuery plugin google charts
 * @copyright (c) 2010 Janusz Kamieński (www.ivellios.toron.pl)
 * @license CC Attribution Works 3.0 Poland - http://creativecommons.org/licenses/by/3.0/pl/deed.en_US
 * @example Visit http://www.ivellios.toron.pl/technikalia/demos/gvChart/ for more informations about this jQuery plugin
 */
(function (jQuery){
	jQuery.fn.gvChart = function(settings){

	defaults={
		hideTable: true,
		chartType: 'AreaChart',
		chartDivID: 'gvChartDiv',
		gvSettings: null
	};
	
	var el = document.createElement('div');
	jQuery(el).insertBefore(this);
	gvChartCount++;
	gvChartID = defaults.chartDivID+gvChartCount;
	jQuery(el).attr('id',gvChartID);
	jQuery(el).addClass('gvChart');

	if(settings){
	jQuery.extend(defaults,settings);
	}
	
	if(defaults.hideTable)
		$(this).hide();

	var data = new google.visualization.DataTable();

	// add X label
	data.addColumn('string','X labels');

	var a = new Array();

	var headers = $(this).find('thead').find('th');
	var rows = $(this).find('tbody').find('tr');

	rows.each(function(index){
		data.addColumn('number',$(this).find('th').text());
	});

	data.addRows(headers.length-1);

	headers.each(function(index){
		if(index){
			data.setCell(index-1, 0, $(this).text());
		}
	});

	rows.each(function(index){
			$(this).find('td').each(function(index2){
				data.setCell(index2, index+1, parseFloat($(this).text()));
			});
	});
	
	chartSettings = {
		title : $(this).find('caption').text()
	};
	
	if(defaults.gvSettings){
		jQuery.extend(chartSettings,defaults.gvSettings);
	}
	
	eval("var chart = new google.visualization."+defaults.chartType+"(document.getElementById('"+gvChartID+"'))");
	chart.draw(data, chartSettings);
  }
})(jQuery);


function gvChartInit(){
	gvChartCount = 0;
	google.load('visualization', '1', {packages: ['corechart']});
}

;/**
 * object language, date , and dashboard are init in all_content.twig for translation
 *
 */

var xhr_object;
var p4 = {};
// jquery tab object
var $tabs;
//the number of the selected tab
var selected_tab;
//class of the selected init to -1 by default = no class
var class_selected_tab = -1;
//save the value of the previous limit
var save_limit;
var bodySize = {
    x: 0,
    y: 0
};

//#############START DOCUMENT READY ######################################//
$(document).ready(function () {
    //resize window
    $(window).bind('resize', function () {
        resize();
    });
    //do tabs and resize window on show
    $('#mainTabs:visible').tabs({
        activate: function () {
            resize();
        }
    });
    resize();
    //datepicker
    reportDatePicker();
    dashboardDatePicker();
    bindEvents();

    $("a.select-all").bind("click", function (e) {
        $("ul.multiselect .coll-checkbox", $(this).closest('.form2')).prop("checked", true);
    });

    $("a.deselect-all").bind("click", function (e) {
        $("ul.multiselect .coll-checkbox", $(this).closest('.form2')).prop("checked", false);
    });

    // toggle is deprecated:
    var hasMultiSelectionGroup = false;
    $(".multiselect-group").on('click', function () {

        if( hasMultiSelectionGroup === true) {
            var $this = $(this);
            var groupId = $this.data('group-id');
            $(".checkbox-" + groupId, $this.closest('.form2')).prop("checked", false);
            hasMultiSelectionGroup = false;
        } else {
            var $this = $(this);
            var groupId = $this.data('group-id');
            $(".checkbox-" + groupId, $this.closest('.form2')).prop("checked", true);
            hasMultiSelectionGroup = true;
        }
    });
});
//#############END DOCUMENT READY ######################################//

/**
 *
 * Tous les binds sur le report
 */
function bindEvents() {
    $('#dminDash, #dmaxDash').datepicker({
        changeMonth: true,
        changeYear: true,
//        dateFormat: 'dd-mm-yy',
        dateFormat: 'yy-mm-dd',
        numberOfMonths: 1,
        maxDate: "-0d"
    });

    $(".submit-dashboard").click(function() {
        loadDash();
    });
    //load all the report
    $('form input.formsubmiter').bind('click', function () {
        submiterAction($(this));
    });

    $('form select.formsubmiter').bind('change', function () {
        submiterAction($("option:selected", $(this)));
    });

    //reload the content by pressing enter key, it concerns the number of result by report
    $('form .entersubmiter').bind('keypress', function (event) {
        if (event.keyCode == '13') {
            $("#DOC-input").prop("checked", "checked").trigger('click');
        }
    });
    //action on table links
    $('td a:visible').bind('click', function () {
        tableLinkAction($(this));
    });
    //action on a none radio  input
    $('.inside-container form input:not(:radio)').bind('click', function () {
        removeChecked($(this));
    });
    //action a radio input
    $('.inside-container form input:radio').bind('change', function () {
        showOption($(this));
    });
    //hide report menu
    $("button.hided").button({
        icons: {
            primary: 'ui-icon-triangle-1-n'
        },
        text: false
    }).unbind("click").bind("click", function () {
            hideMenu();
        });
    // show report menu
    $("button.showed").button({
        icons: {
            primary: 'ui-icon-triangle-1-s'
        },
        text: false
    }).unbind("click").bind("click", function () {
            showMenu();
        });
}

function reportDatePicker() {
    var dates = $('.dmin, .dmax').datepicker({
        defaultDate: -10,
        changeMonth: true,
        changeYear: true,
//        dateFormat: 'dd-mm-yy',
        dateFormat: 'yy-mm-dd',
        numberOfMonths: 3,
        maxDate: "-0d",
        onSelect: function (selectedDate, instance) {
            var option = $(this).hasClass("dmin") ? "minDate" : "maxDate";
            var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
            $(dates).not(':hidden').not(this).datepicker("option", option, date);
        }
    });
}

function dashboardDatePicker() {
    $(function () {
        $('.dminDash, .dmaxDash').datepicker({
            defaultDate: -3,
            changeMonth: true,
            changeYear: true,
//            dateFormat: 'dd-mm-yy',
            dateFormat: 'yy-mm-dd',
            numberOfMonths: 3,
            maxDate: "-0d"
        });
    });
}
//hide and resize content
function hideMenu() {
    $('.hided').hide();
    $(".showed").show();
    $(".form").slideToggle("slow", function () {
        bodySize.y = $(document).height();
        $('.answers:visible').height(Math.round(bodySize.y - $('.answers:visible').position().top - 30));
    });
}

function showMenu() {
    bodySize.y = $('#mainContainer').height();
    $('.showed').hide();
    $(".hided").show();
    $(".form").slideToggle("slow", function () {
        bodySize.y = $(document).height();
        $('.answers:visible').height(Math.round(bodySize.y - $('.answers:visible').position().top - 30));

    });
}

function submiterAction(domSubmiter) {
    var form = domSubmiter.closest('form');
    var container = domSubmiter.closest('.inside-container');

    var data = form.serializeArray();

    data.push({name: "action", value: domSubmiter.data('action')});

    //check if a base is selected, pop an alert message if not
    if (!isOneBaseSelected(form)) {
        alertBase();
    }
    else {
        var request = form.data("request");

        if (request && typeof(request.abort) == 'function') {
            request.abort();
        }

        request = $.ajax({
            type: "POST",
            url: "/report/init",
            data: data,
            beforeSend: function () {
                container.find('.content').empty();
                container.find('.answers').addClass('onload');
            },
            success: function (data) {
                container.find('.answers').removeClass('onload');
                //load data
                container.find('.content').empty().append(data);
                //init to 0;
                initSelectedTab();
                //init tab with the loaded content
                initTabs(container);
                //open selected tab
                openSelectedTab();
                //start position
                right = getScrollerStartPosition(selected_tab);
                //scroller
                $(".horizontal-scroller:visible").nicoslider({
                    start: right
                });
            }
        });

        form.data('request', request);
    }
}

function initTabs(wrapper) {
    $tabs = wrapper.find('div.tabs').tabs({
        create: function (event, ui) {
            //define the div where the table is loaded
            load = $(ui.panel).find('.load');
            //define the form that contain all parameters to build the table in the loaded div
            form = $(ui.panel).find("form");
            //serialize all the form values
            f_val = form.serialize(true);
            //build the table
            update_tab(load, form, f_val);
        },
        activate: function (event, ui) {
            //define the div where the table is loaded
            load = $(ui.newPanel).find('.load');
            //define the form that contain all parameters to build the table in the loaded div
            form = $(ui.newPanel).find("form");
            //serialize all the form values
            f_val = form.serialize(true);
            //build the table
            update_tab(load, form, f_val);
        }
    });
}

function openFirstTab() {
    $('.tabb:visible li').eq(0).find("a").trigger("click");
}

function openSelectedTab() {
    if (class_selected_tab == -1) {
        openFirstTab();
    }
    else if (typeof class_selected_tab == "undefined") {
        openFirstTab();
    }
    else {
        theclass = class_selected_tab.split(" ");
        if ($('.' + theclass[0] + ':visible').length > 0) {
            $('.' + theclass[0] + ':visible').find("a").trigger("click");
        }
        else {
            openFirstTab();
        }
    }
}

function initSelectedTab() {
    if (typeof(selected_tab) == 'undefined') {
        selected_tab = 0;
    }
}

function alertBase() {
    $('body').append("<div id='dialog'><div>");
    $('#dialog').dialog({
        title: language.choix_collection,
        height: 0,
        width: 380,
        draggable: false,
        modal: true,
        resizable: false,
        hide: 'explode',
        close: function (ev, ui) {
            $(this).dialog('destroy').remove();
        }
    });
}

function isOneBaseSelected(form) {
    if (!form.find("ul.multiselect input:checked").length) {
        return false;
    }
    else {
        return true;
    }
}

function showOption(domInput) {
    var opt = domInput.closest('div').find('.options');
    domInput.closest('form').find('.options').hide();
    if (domInput.get(0).checked) {
        opt.show();
    }
}

function removeChecked(domInput) {
    domInput.closest("form").find('input:radio:visible:checked').prop("checked", false);
}
function tableLinkAction(domLink) {
    var cl = domLink.attr("id");
    var arr = cl.split('_');
    var w = $('#mainTabs:visible').width();
    if (isDocumentLink(domLink)) {
        $.ajax({
            type: "POST",
            url: "/report/informations/document",
            dataType: "json",
            data: ({
                tbl: "what",
                rid: arr[1],
                sbasid: arr[2],
                collection: "",
                from: "DASH",
                dmin: date.dmin,
                dmax: date.dmax
            }),
            success: function (data) {
                modalBox(data);
            }
        });
    }
    else {
        $.ajax({
            type: "POST",
            url: "/report/informations/user",
            dataType: "json",
            data: ({
                tbl: "infouser",
                user: arr[1],
                sbasid: 1,
                collection: "",
                from: "",
                dmin: date.dmin,
                dmax: date.dmax
            }),
            success: function (data) {
                modalBox(data);
            }
        });
    }
}

function isDocumentLink(domLink) {
    return domLink.hasClass("hasSbas");
}

function modalBox(data) {
    $('body').append("<div id='dialog'>" + data.rs + "</div>");
    $('#dialog').dialog({
        title: data.title,
        width: 860,
        modal: true,
        close: function (ev, ui) {
            $(this).dialog('destroy').remove();
        }
    });
}

function getScrollerStartPosition(selected_tab) {
    right = 0;
    if (parseInt(selected_tab) === 0) {
        right = 0;
    }
    else {
        $('.tabb:visible li').each(function (index) {
            if (index == selected_tab) {
                return false;
            }
            right += $(this).width();
        });
    }
    return right;
}

function drawCharts() {
    if ($('#mytabledaytotal').length > 0) {
        $('#mytabledaytotal').gvChart({
            chartType: 'LineChart',
            gvSettings: {
                titleTextStyle: {
                    color: '#FF8D1C',
                    fontSize: '20'
                },
                vAxis: {
                    title: dashboard.title_connexion,
                    textStyle: {
                        fontSize: '10',
                        color: '#AAAAAA'
                    }
                },
                hAxis: {
                    title: dashboard.title_jour,
                    textStyle: {
                        fontSize: '10',
                        color: '#AAAAAA'
                    },
                    tooltipTextStyle: {
                        fontSize: 4
                    },
                    showTextEvery: 4
                },
                lineWidth: 1,
                pointSize: 2,
                backgroundColor: '#696969',
                width: 800,
                height: 350
            }
        });
    }

    if ($('#mytablehour').length > 0) {
        $('#mytablehour').gvChart({
            chartType: 'LineChart',
            gvSettings: {
                colors: ['white', '#FFFFFF'],
                titleTextStyle: {
                    color: '#FF8D1C',
                    fontSize: '20'
                },
                vAxis: {
                    title: dashboard.title_connexion,
                    textStyle: {
                        fontSize: '10',
                        color: '#AAAAAA'
                    }
                },
                hAxis: {
                    title: dashboard.title_heure,
                    textStyle: {
                        fontSize: '10',
                        color: '#AAAAAA'
                    },
                    tooltipTextStyle: {
                        fontSize: 4
                    },
                    slantedTex: true,
                    slantedTextAngle: 90,
                    maxAlternation: 1,
                    showTextEvery: 1
                },
                lineWidth: 1,
                pointSize: 3,
                backgroundColor: '#696969',
                width: 800,
                height: 350
            }
        });
    }

    if ($('#mytableadded').length > 0) {
        $('#mytableadded').gvChart({
            chartType: 'ColumnChart',
            gvSettings: {
                colors: ['white', '#FFFFFF'],
                titleTextStyle: {
                    color: '#FF8D1C',
                    fontSize: '20'
                },
                vAxis: {
                    title: dashboard.title_doc_add,
                    textStyle: {
                        fontSize: '10',
                        color: '#AAAAAA'
                    }
                },
                hAxis: {
                    title: dashboard.title_jour,
                    textStyle: {
                        fontSize: '10',
                        color: '#AAAAAA'
                    },
                    tooltipTextStyle: {
                        fontSize: 4
                    },
                    showTextEvery: 4
                },

                legend: 'none',
                lineWidth: 1,
                pointSize: 3,
                backgroundColor: '#696969',
                width: 800,
                height: 350
            }
        });
    }

    if ($('#mytableedited').length > 0) {
        $('#mytableedited').gvChart({
            chartType: 'ColumnChart',
            gvSettings: {
                colors: ['white', '#FFFFFF'],
                titleTextStyle: {
                    color: '#FF8D1C',
                    fontSize: '20'
                },
                vAxis: {
                    title: dashboard.title_doc_edit,
                    textStyle: {
                        fontSize: '10',
                        color: '#AAAAAA'
                    }
                },
                hAxis: {
                    title: dashboard.title_jour,
                    textStyle: {
                        fontSize: '10',
                        color: '#AAAAAA'
                    },
                    tooltipTextStyle: {
                        fontSize: 4
                    },
                    showTextEvery: 4
                },

                legend: 'none',
                lineWidth: 1,
                pointSize: 3,
                backgroundColor: '#696969',
                width: 800,
                height: 350
            }
        });
    }
}

//unserialize value
function unserialize(str) {
    var n_str = str.split("&");
    var serialised = new Array();
    $.each(n_str, function () {
        var properties = this.split("=");
        serialised[properties[0]] = properties[1];
    });
    return serialised;
}
//pop a dialog box with who download what content
function who() {
    $("td a.bound").unbind("click").bind('click', function () {
        //get form
        var form = $(this).closest(".ui-tabs-panel").find(".report_form");
        //get col
        var col = $(this).closest("td").attr("class");
        //get link value
        var val_a = $(this).html();
        //split link classes
        var arr = $(this).attr("class").split(" ");
        //get usrid
        var usrid = arr[0];
        //get the current tbl
        var tbl = form.find("input[name=tbl]").val();
        //replace the new tbl
        form.find("input[name=tbl]").val("infouser");
        //put the old in the from input
        form.find("input[name=from]").val(tbl);

        if (col == 'user') {
            form.find("input[name=user]").val(usrid);
        }
        else if (tbl == 'CNXB') {
            form.find("input[name=tbl]").val("infonav");
            form.find("input[name=user]").val(val_a);
            form.find("input[name=on]").val(col);
        }
        else {
            form.find("input[name=user]").val(val_a);
            form.find("input[name=on]").val(col);
        }
        //load content
        $.ajax({
            type: "POST",
            url: form.find("input[name=action]").val(),
            dataType: "json",
            data: form.serializeArray(),
            success: function (data) {
                //replace tbl with the from tbl
                form.find("input[name=tbl]").val(tbl);
                //pop the dialog window
                dialog_record(form, data.rs, data.title, tbl);
            }
        });
    });
}
//group by the element of each column
function group() {
    $("a.groupby").unbind("click").bind("click", function () {
        var form = $(this).closest(".ui-tabs-panel").find(".report_form");
        var col = $(this).attr('class');
        var tbl = form.find("input[name=tbl]").val();
        form.find("input[name=groupby]").val(col);
        $.ajax({
            type: "POST",
            url: form.find("input[name=action]").val(),
            dataType: "json",
            data: form.serializeArray(),
            success: function (data) {
                form.find("input[name=tbl]").val(tbl);
                form.find("input[name=groupby]").val("");
                dialog_record(form, data.rs, data.title, tbl);
            }
        });
    });
}
//pop & load the record box informations
function what() {
    $(".record_id a").unbind("click").bind('click', function () {
        var form = $(this).closest(".ui-tabs-panel").find(".report_form");
        var rid = $(this).html();
        var arr = $(this).attr("class").split(" ");
        var usrid = arr[0];
        var tbl = form.find("input[name=tbl]").val();
        form.find("input[name=from]").val(tbl);
        form.find("input[name=tbl]").val("what");
        form.find("input[name=rid]").val(rid);
        form.find("input[name=user]").val(usrid);
        $.ajax({
            type: "POST",
            url: "/report/informations/document",
            dataType: "json",
            data: form.serializeArray(),
            success: function (data) {
                dialog_record(form, data.rs, data.title, tbl);
            }
        });
    });
}
//construct the dialog_record box
function dialog_record(form, p_message, p_title, tbl) {
    //get size attribute
    var h = $(document).height();
    var w = $('#mainTabs:visible').width();
    p_title = p_title || "";

    $('body').append("<div id='dialog'>" + p_message + "</div>");
    var data_form = form.serializeArray();
    var dial = $('#dialog');
    dial.data('dataForm', form);
    dial.dialog({
        title: p_title,
        height: h,
        width: w,
        modal: true,
        resizable: false,
        close: function (ev, ui) {
            form.find("input[name=tbl]").val(tbl);
            form.find("input[name=on]").val("");
            $(this).dialog('destroy').remove();
        }
    });
    csv();
}
//construct the dialog box filters.
function alert_dialog_filter(submit, form, p_message, p_title) {
    var buttons = {};

    p_title = p_title || "";
    $('body').append("<div id='dialog'>" + p_message + "</div>");
    buttons[language.valider] = function () {
        var value = $("select[name='filtre'] option:selected").val();
        form.find("input[name=filter_value]").val(value);
        var f_val = form.serialize(true);
        update_tab(submit, form, f_val);
        form.find("input[name=filter_column]").val("");
        form.find("input[name=filter_value]").val("");
        $(this).dialog('destroy').remove();
    };
    $('#dialog').dialog({
        title: p_title,
        width: 400,
        modal: true,
        resizable: false,
        draggable: false,
        buttons: buttons,
        close: function (ev, ui) {
            $(this).dialog('destroy').remove();
        }
    });
}
//construct the configuration dialog box
function alert_dialog_conf(submit, form, p_message, p_title) {
    var w = $('#mainTabs:visible').width();
    var buttons = {};

    buttons[language.valider] = function () {
        var idChecked = new Array();

        $("#dialog input:checked").each(function (id) {
            idChecked[id] = $(this).val();
        });
        var list_column = ",";
        $.each(idChecked, function (key, val) {
            list_column += val + ",";
        });
        form.find("input[name=list_column]").val(list_column);
        f_val = form.serialize(true);
        if (idChecked.length == 0) {
            alert("Vous devez cocher au minimum une case");
            return false;
        }
        else {
            update_tab(submit, form, f_val);
            $(this).dialog('destroy').remove();
        }
    };

    p_title = p_title || "";
    $('body').append("<div id='dialog'>" + p_message + "</div>");
    $('#dialog').dialog({
        title: p_title,
        width: w,
        modal: true,
        buttons: buttons,
        close: function (ev, ui) {
            $(this).dialog('destroy').remove();
        }
    });
}
//load the content of the filter box
function dofilter(submit, form, f_val) {
    $("a.filter").unbind("click").bind("click", function () {
        var col = $(this).attr('class');
        form.find("input[name=filter_column]").val(col);
        form.find("input[name=liste]").val("on");
        $.ajax({
            type: "POST",
            url: form.find("input[name=action]").val(),
            dataType: "json",
            data: form.serializeArray(),
            success: function (data) {
                form.find("input[name=liste]").val("off");
                alert_dialog_filter(submit, form, data.diag, data.title);
            }
        });
    });
}
//pop & load the content of the dialog_conf window
function conf(submit, form, f_val) {
    $("a.config").unbind("click").bind("click", function () {
        form.find("input[name=conf]").val("on");
        $.ajax({
            type: "POST",
            url: form.find("input[name=action]").val(),
            dataType: "json",
            data: form.serializeArray(),
            success: function (data) {
                form.find("input[name=conf]").val("off");
                alert_dialog_conf(submit, form, data.liste, data.title);
            }
        });
    });
}
//load the next page of data array
function next(submit, form, f_val, data) {
    form.find(".next").unbind('click').bind('click', function () {
        form.find("input[name=page]").attr("value", data.next);
        form.find("input[name=liste_filter]").attr("value", data.filter);
        f_val = form.serialize(true);
        update_tab(submit, form, f_val);
        return false;
    });
}
//load the previous page of data array
function prev(submit, form, f_val, data) {
    form.find(".prev").unbind('click').bind('click', function () {
        form.find("input[name=page]").attr("value", data.prev);
        form.find("input[name=liste_filter]").attr("value", data.filter);
        f_val = form.serialize(true);
        update_tab(submit, form, f_val);
    });
    return false;
}
//print the table when click on the print link
function print() {
    $("a.jqprint").unbind("click").bind("click", function () {
        var $table = $(this).closest(".report-table");
        var $graph = $(this).closest(".graph");

        if ($graph.length > 0) {
            $graph.jqprint();
        } else {
            $table.jqprint();
        }
    });
}

function csv() {
    var button = $("#export_csv");

    button.unbind("click").bind("click", function (e) {
        e.preventDefault();
        var $this = $(this);

        if ($this.closest("#dialog").length > 0) {
            var $form = $("#dialog").data("dataForm");
        } else {
            var $form = $this.closest(".ui-tabs-panel").find(".report_form");
        }

        //clone form and submit
        var clone = $form.clone().appendTo($this);

        clone.attr("action", $form.find("input[name=action]").val())
            .attr("method",'POST')
            .removeAttr("onsubmit")
            .find("input[name=printcsv]").val("on");

        $(clone).submit().remove();
    });
}


//order the array by DESC or ASC when clicking a column
function orderArray() {
    $('.orderby').unbind("click").bind('click', function () {
        var $this = $(this);
        var champ = $(this).parent().attr('class');
        var submit_click = $this.closest(".report-table").parent();
        var form_click = submit_click.parent().find("form");
        var order = 'asc';
        if (form_click.find("input[name=order]").val() == "") {
            order = "asc";
        }

        if (form_click.find("input[name=order]").val() == "asc") {
            order = "desc";
            $this.find('.asc').hide();
        }
        else {
            order = "asc";
            $this.find('.desc').hide();
        }
        form_click.find("input[name=order]").val(order);
        form_click.find("input[name=champ]").val(champ);
        var f_val = form_click.serialize(true);
        update_tab(submit_click, form_click, f_val);

        return false;
    });
}
//show hide prev & next or both according to the result
function navigation(form, prev, next, display_nav) {
    if (prev == 0) {
        form.find("input[name=prev]").hide();
    }
    else {
        form.find("input[name=prev]").show();
    }

    if (next == false) {
        form.find("input[name=next]").hide();
    }
    else {
        form.find("input[name=next]").show();
    }

    if (display_nav == false || ((prev == 0) && (next == false))) {
        form.hide();
    }
}
//color filter'slink if a filter is active
function colorFilter(col) {
    if ($.isArray(col)) {
        $.each(col, function () {
            $("a." + this).filter("a.filter").css("color", "#0000FF");
        });
    }
}
//show hide desc or asc arrow according to the order of the table
function arrow(form) {
    var cl = form.find("input[name=champ]").val();

    if (cl != "") {
        var th = $("th." + cl + ":visible");
        th.css("color", "white");
        if (form.find("input[name=order]").val() == "asc") {
            th.find('.asc').hide();
        }
        else if (form.find("input[name=order]").val() == "desc") {
            th.find('.desc').hide();
        }
    }
}
//load default page and number of result if the user seizes crazy things in this inputs
function page(form, lim, array_val) {
    var current_lim = form.find("input[name=limit]").val();

    if (current_lim < 1 || Math.floor(current_lim).toString() != current_lim.toString()) {
        current_lim = 30;
        form.find("input[name=limit]").attr("value", current_lim);
    }

    if (current_lim != lim) {
        form.find("input[name=page]").attr("value", "1");
    }
    else {
        if (array_val["page"] < 1 || Math.floor(array_val["page"]).toString() != array_val["page"].toString()) {
            array_val["page"] = 1;
        }
        form.find("input[name=page]").attr("value", array_val["page"]);
    }
}
//do a submit button to load new users conf
function go(submit, form, f_val, data) {
    $(".submiter").bind("click", function () {
        form.find("input[name=liste_filter]").attr("value", data.filter);
        form.find("input[name=action]").attr("value", $(this).data('action'));
        f_val = form.serialize(true);
        update_tab(submit, form, f_val);
    });
}

function loadDash() {
    var $form = $("#dashboard-form");
    $.ajax({
        url     : $form.attr('action'),
        type    : $form.attr('method'),
        dataType: 'json',
        data    : $form.serializeArray(),
        beforeSend: function() {
            resize();
            $("#dashboard").empty().addClass("loading");
        },
        success : function( data ) {
            $("#dashboard").empty().append(data.html);
            drawCharts();
            $('td a:visible').bind('click', function () {
                tableLinkAction($(this));
            });
        },
        error   : function( xhr, err ) {
        },
        timeout: function(){
        }
    }).done(function() {
        $("#dashboard").removeClass("loading");
    });
    return false;
}

//submit is the div where we want to load the updated tab
//form is the current form
//f_val is the serialized form
function update_tab(submit, form, f_val) {
    //unserialize the form values
    var array_val = unserialize(f_val);
    //attribute the current page & check values
    page(form, save_limit, array_val);
    //attribute the current filter
    form.find("input[name=liste_filter]").attr("value", array_val["liste_filter"]);

    var datas = form.serializeArray();

    $.ajax({
        type: "POST",
        url: form.find("input[name=action]").val(),
        dataType: "json",
        data: datas,
        beforeSend: function () {
            submit.empty();
            submit.closest('.answers').addClass('onload');
            form.hide();
        },
        success: function (data) {
            //remove loader
            submit.closest('.answers').removeClass('onload');
            //show form
            form.show();

            //attribute the new page
            form.find("input[name=page]").attr("value", data.page);
            //attribute the new filter
            form.find("input[name=liste_filter]").attr("value", data.filter);
            //save current limit
            save_limit = data.limit;
            //load the result
            submit.empty().append(data.rs);
            //get selected li index
            if ($tabs.data("ui-tabs")) {
                var selected_tab = $tabs.tabs('option', 'active');
            }
            if (typeof(selected_tab) === 'undefined') {
                selected_tab = 0;
            }
            class_selected_tab = $('.tabb:visible li').eq(selected_tab).attr('class');
            //hide show the next and previous button according to the results
            navigation(form, data.prev, data.next, data.display_nav);
            //color the filter link if active
            colorFilter(data.col);
            //load the next array
            next(submit, form, f_val, data);
            //load the previous one
            prev(submit, form, f_val, data);
            //submit new array
            go(submit, form, f_val, data);
            //load the who array
            who();
            //load the what array
            what();
            //load the group by array
            group();
            //load the array with new filters
            dofilter(submit, form, f_val);
            //load the configuration array
            conf(submit, form, f_val);
            //print the array
            print();
            //export csv
            csv();
            //load the new array with new order
            orderArray();
            //hide show desc or asc arrow
            arrow(form);

            drawPlatformAndNavigatorChart(datas);
        }
    });
}


function drawPlatformAndNavigatorChart(data) {
    $.each(data, function (k, v) {
        if (v.name == "tbl" && v.value == "CNXB") {
            $(".navi").each(function () {
                $(this).gvChart({
                    chartType: 'PieChart',
                    hideTable: true,
                    gvSettings: {
                        width: 890,
                        height: 300,
                        backgroundColor: "#F6F2F1",
                        is3D: true,
                        legend: 'bottom'
                    }
                });
            });
        }
        else if (v.name == "tbl" && v.value == "SITEACTIVITY") {
            $(".tblsite").gvChart({
                chartType: 'LineChart',
                gvSettings: {
                    vAxis: {
                        title: language.connexion
                    },
                    hAxis: {
                        title: language.heure
                    },
                    width: 890,
                    height: 300,
                    backgroundColor: "#F6F2F1"
                }
            });
        }
    });
}

//resize report div
function resize() {
    bodySize.y = $('#mainContainer').innerHeight();
    bodySize.x = $('#mainContainer').innerWidth();

    $('.answers:visible').height(Math.round(bodySize.y - $('.answers:visible').offset().top));
};

function pollNotifications() {
    $.ajax({
        type: "POST",
        url: "/session/notifications/",
        dataType: 'json',
        data: {
            module: 10,
            usr: usrId
        },
        error: function () {
            window.setTimeout("pollNotifications();", 10000);
        },
        timeout: function () {
            window.setTimeout("pollNotifications();", 10000);
        },
        success: function (data) {
            if (data) {
                manageSession(data);
            }
            var t = 120000;
            if (data.apps && parseInt(data.apps) > 1) {
                t = Math.round((Math.sqrt(parseInt(data.apps) - 1) * 1.3 * 120000));
            }
            window.setTimeout("pollNotifications();", t);
            return;
        }
    });
};

window.setTimeout("pollNotifications();", 10000);
